2

我正在为模型实现多张照片上传,所以我使用回形针和nested_form gem

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

我被困住了。

4

1 回答 1

4

尝试更改导致以下错误的行:

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