Rails - 如何迭代关联的对象?

问题描述:

我想在网页上显示一个新的对象和与它关联的每个插图。 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 

您正在将for的语法与每种方法很少混用。你应该这样做

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