2013-03-21 55 views
2

我正在爲模型實施多張照片上傳,因此我正在使用回形針和nested_form寶石無效的關聯。請確保accep_nested_attributes_for用於:照片關聯

屬性中有很多照片。

這是物業模型。

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

嘗試改變行給出了一個錯誤以下幾點:

= f.link_to_add "Add", :photos 
+0

我所做的事,一個愚蠢的錯誤。謝啦!! – 2013-03-21 19:59:00

+1

這不適合我,你知道另一種解決方案嗎? – Jngai1297 2013-10-22 17:15:52