2010-03-15 62 views
0

我似乎获得错误:索引视图中的嵌套属性?

uninitialized constant Style::Pic 

当我试图渲染到索引嵌套对象观看演出的观点是好的。

class Style < ActiveRecord::Base 
#belongs_to :users 
has_many :style_images, :dependent => :destroy 
accepts_nested_attributes_for :style_images, 
:reject_if => proc { |a| a.all? { |k, v| v.blank?} } #found this here http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes 

has_one :cover, :class_name => "Pic", :order => "updated_at DESC" 
accepts_nested_attributes_for :cover 
end 


class StyleImage < ActiveRecord::Base 
belongs_to :style 
#belongs_to :style_as_cover, :class_name => "Style", :foreign_key => "style_id" 
has_attached_file :pic, 
        :styles => { :small => "200x0>", 
           :normal => "600x> " } 

validates_attachment_presence :pic 
#validates_attachment_size :pic, :less_than => 5.megabytes 

end 



<% for style_image in @style.style_images %> 
<li><%= style_image.caption %></li> 


<div id="show_photo"> 


    <%= image_tag style_image.pic.url(:normal) %></div> 

<% end %> 

正如你可以看到从上面的主力车型风格有很多style_images,所有这些style_images显示在显示视图,但是,在索引视图我希望显示一个图像这一直名字,并充当每种风格显示的封面。

在索引控制器I曾尝试以下:

class StylesController < ApplicationController 
    layout "mini" 
    def index 
    @styles = Style.find(:all, 
    :inculde => [:cover,]).reverse 

    respond_to do |format| 
     format.html # index.html.erb 
     format.xml { render :xml => @styles } 
    end 
    end 

和索引

<% @styles.each do |style| %> 


<%=image_tag style.cover.pic.url(:small) %> 

<% end %> 



class StyleImage < ActiveRecord::Base 
belongs_to :style 
#belongs_to :style_as_cover, :class_name => "Style", :foreign_key => "style_id" 
has_attached_file :pic, 
        :styles => { :small => "200x0>", 
           :normal => "600x> " } 

validates_attachment_presence :pic 
#validates_attachment_size :pic, :less_than => 5.megabytes 

end 

在style_images表有一个cover_id也。

从你可以看到,我已经在控制器和模型中包含了封面。 我知道我在哪里错了!

如果有人能帮忙请做!

回答

0

您必须修复您的:cover关联定义,如下所示。

has_one :cover, :class_name => "StyleImage", :order => "updated_at DESC" 

我看到您的设计中的另一个潜在问题。您使用相同的外键(style_id)指向同一个表的has_manyhas_one关联(style_id)。

class Style < ActiveRecord::Base 
    has_many :style_images 
    has_one :cover, :class_name => "StyleImage", :order => "updated_at DESC" 
end 

对于:cover协会工作,封面图片必须具有在style_images表中的最大更新时间。这不是一个非常安全的假设。您可以如下改进:

style_images表添加一个新列以存储图像类型。现在,您的关联可以改写为:

has_one :cover, :class_name => "StyleImage", :conditions => {:itype => "cover"} 

OR

更改has_one协会belongs_to和存储外键(style_image_id)在styles表,即

class Style < ActiveRecord::Base 
    has_many :style_images 
    belongs_to :cover, :class_name => "StyleImage" 
end 
+0

PIC是在数据库的style_images表中。 – MrThomas 2010-03-15 16:17:16