【问题标题】:Invalid association. Make sure that accepts_nested_attributes_for is used for :photos association无效的关联。确保 accept_nested_attributes_for 用于 :photos 关联
【发布时间】:2013-03-21 13:54:52
【问题描述】:

我正在为模型实现多张照片上传,因此我使用的是回形针和nested_form gems

一个属性有很多照片。

这是属性模型。

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

我被卡住了。

【问题讨论】:

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


    【解决方案1】:

    尝试将出现错误的行更改为以下内容:

    = f.link_to_add "Add", :photos
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多