2013-02-28 92 views
0

我想在網頁上顯示一個新的對象和與它關聯的每個插圖。 1.我不知道如何正確編寫代碼來獲得小說的相關插圖。 2.我不知道如何正確引用插圖對象的屬性。我認爲我的錯誤可能來自無關的事。Rails - 如何迭代關聯的對象?

新模式:

Class Novel < ActiveRecord::Base 
    has_many :illustrations 
    attr_accessible :id, :name, :author, :edition, :publisher, :publication_city, :publication_date, :illustrations 
    validates :id, uniqueness: true, presence: true 
    validates :name, :author, :edition, :publisher, :publication_city, :publication_date,  presence: true 
end 

插圖型號:

class Illustration < ActiveRecord::Base 
    belongs_to :novel 
    attr_accessible :id, :illustrator, :image_url, 
    :image_thumbnail_url, :name, :source, :tags, 
    :description, :novel_id 
    validates :id, uniqueness: true 
    validates :name, :source, presence: true 
    validates :image_url, 
    format: { with: %r{\.{gif|.jpg|.png}\Z}i, 
    message: 'must be a URL for .gif, .jpg, or .png'} 
    validates :image_thumbnail_url, 
    format: { with: %r{\.{gif|.jpg|.png}\Z}i, 
    message: 'must be a URL for .gif, .jpg, or .png'} 
    validates :illustrator, :tags, :description, presence: true 
end 

小說指數類:

<% if notice %> 
<p id="notice"><%= notice %></p> 
<% end %> 

<h1 style="padding-left:25px">Archive Overview</h1> 

<% @novels.each do |novel| %> 
<%= illustrations = novel.map(&:illustration) %> 
<div class="row"> 
    <div class="span3" style="padding:0px 0px 25px 25px"> 
     <%= link_to novel.name, novel %> 
    </div> 
    <div class="span4"> 
     <p><%= novel.author%></p> 
     <p><%= novel.publisher %></p> 
     <p><%= novel.publication_date %></p> 
    <div class="span5"> 
     <ul>  
      <% for illustrations.each do |illustration| %> 
      <li><%= illustration.name %></li> 
      <% end %> 
     </ul> 
    </div> 
    </div> 
</div> 
<% end %> 

我對illustrations.each循環語法的任意組合得到的錯誤:

SyntaxError in Booklist#index 

Showing /home/joe/Documents/workspace/archive/app/views/booklist/index.html.erb where line #21 raised: 

/home/joe/Documents/workspace/archive/app/views/booklist/index.html.erb:21: syntax error, unexpected '\n', expecting tCOLON2 or '[' or '.' 
Extracted source (around line #21): 

18:    <ul>  
19:     <% for illustrations.each do |illustration| %> 
20:     <li><%= illustration.name %></li> 
21:     <% end %> 
22:    </ul> 
23:   </div> 
24:   </div> 
Trace of template inclusion: app/views/booklist/index.html.erb 

Rails.root: /home/joe/Documents/workspace/archive 

回答

2

您正在將for的語法與每種方法很少混用。你應該這樣做

<% illustrations.each do |illustration| %> 
    <li><%= illustration.name %></li> 
<% end %>