2

モデルに複数の写真のアップロードを実装しているため、paperclip と nested_form の gem を使用しています

プロパティには多くの写真があります。

これがプロパティモデルです。

class Property < ActiveRecord::Base
  attr_accessible :photos_attributes, :type, :price, :address, :desc, :category_id, :location_id, :user_id
  TYPE = {
    rent: "rent",
    sale: "sale"
  }

  has_many :photos, dependent: :destroy
  belongs_to :category
  belongs_to :location
  belongs_to :user
  accepts_nested_attributes_for :photos, reject_if: lambda { |t| t[:photo].nil? }, allow_destroy: true
  acts_as_taggable
end

これは写真のモデルです

class Photo < ActiveRecord::Base
  attr_accessible :property_id
  belongs_to :property, dependent: :destroy

  has_attached_file :photo, styles: {small: "100x100>", medium: "300x300>"},
                    url: "/assets/products/:id/:style/:basename.:extension",
                    path: ":rails_root/public/assets/photos/:id/:style/:basename.:extension"

  validates_attachment_size :photo, less_than: 5.megabytes
  validates_attachment_content_type :photo, content_type: ["image/jpeg", "image/png", "image/x-png", "image/pjpeg"]
end

そして、私のスリムな見方は

= nested_form_for @property, html: {multipart: true} do |f|
  = f.fields_for :photos do |photos_f|
     = photos_f.label :photo
     .file-field-wrap
       .file-field
         = photos_f.file_field :photo
         = photos_f.link_to_remove "Remove"
        = photos_f.link_to_add "Add", :photos  # this line gives error

エラーは Invalid association. Make sure that accepts_nested_attributes_for is used for :photos association.

コンソールで実行すると、キーとしてProperty.new.attributes.keys表示されません。:photos_attributesそれが示している["id", "type", "price", "address", "desc", "created_at", "updated_at", "category_id", "location_id", "user_id"]

ハマった。

4

1 に答える 1

4

エラーが発生する行を次のように変更してみてください。

= f.link_to_add "Add", :photos
于 2013-03-21T16:41:44.830 に答える