关联无效。确保accepts_nested_attributes_for用于:照片关联

时间:2013-03-21 13:54:52

标签: ruby-on-rails paperclip nested-forms

我正在为模型实现多张照片上传,所以我使用了paperclip和nested_form gems

A Property有很多照片。

这是物业模型。

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"]

我被困住了。

1 个答案:

答案 0 :(得分:4)

尝试更改导致错误的行:

= f.link_to_add "Add", :photos