0

エラーが発生しているようです:

uninitialized constant Style::Pic

ネストされたオブジェクトを index ビューにレンダリングしようとすると、show ビューは問題ありません。

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 は show ビューに表示されますが、index ビューでは、名前が付けられ、表示されるカバーとして機能する 1 つの画像を表示したいと考えています。スタイルごとに。

インデックスコントローラーで、次のことを試しました:

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_onestyle_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 に答える