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 都显示在显示视图中,但是,在索引视图中,我希望显示一个已命名的图像,并将作为显示的封面每种风格。

在索引控制器中,我尝试了以下操作:

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。

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

如果有人可以帮助,请做!

4

1 回答 1

0

您必须:cover按如下方式修复关联定义。

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

我在您的设计中发现了另一个潜在问题。您有一个has_many和 一个has_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"}

或者

has_one将关联更改为belongs_to并将外键(style_image_id)存储在styles表中,即

class Style < ActiveRecord::Base
  has_many :style_images
  belongs_to  :cover, :class_name => "StyleImage"
end
于 2010-03-15T16:10:14.803 回答