2012-11-12 99 views
0

我使用多態的關係,因爲我有3個型號是這樣的:Rails的嵌套形式(simple_form_for)幫助的has_many belongs_to的關聯

class Food < ActiveRecord::Base 
    has_many :images, as: :imageable, foreign_key: :imageable_uuid, dependent: :destroy 
    accepts_nested_attributes_for :images, :allow_destroy => true 
end 
class MenuPhoto < ActiveRecord::Base 
    has_one :image, as: :imageable, foreign_key: :imageable_uuid, dependent: :destroy 
    accepts_nested_attributes_for :image 
end 
class Image < ActiveRecord::Base 
    belongs_to :imageable, foreign_key: :imageable_uuid, :polymorphic => true 
end 

所以在我的「菜單照片的形式」,我把它像這樣:

= simple_form_for @menu_photo do |f| 
    = f.simple_fields_for :image_attributes do |d| 
     = d.input :photo, as: :file 
     = f.submit 

當我提交這種形式,它給了我這樣的:

{"menu_photo"=>{ 
    "image_attributes"=> 
     {"photo"=>"user image upload"} 
    } 
} 

這是正確的。因此,在 「食品形式」 我做同樣的:

= simple_form_for @food do |f| 
    = f.simple_fields_for :images_attributes do |d| 
     = d.input :photo, as: :file 
     = f.submit 

我期待什麼:

{"food"=>{ 
    "images_attributes"=>[ 
     {"photo"=>"user image upload one"}, 
     {"photo"=>"user image upload two"} 
    ]} 
} 

我得到了什麼:

{"food"=>{ 
    "images_attributes"=> 
     {"photo"=>"user image upload one"} 
    } 
} 

這給了我一個錯誤。任何關於這個的解決方案?

+0

你是什麼意思'相同'?它有同樣的錯誤?如果是這樣,發佈您的模型和控制器的更多信息,以幫助。 – Thanh

+0

@KienThanh:很相似。我希望「link_attributes」是has_many belongs_to關聯中的一個數組,但它只給了我一個簡單的哈希值(我期望有一個哈希數組)。那是什麼錯誤。哦,順便說一下,我使用多態結構。 –

+0

不,'has_many'和'belongs_to'關聯可以根據需要給出許多散列(實際上是一個散列數組,就像您期望的那樣)。選中此[Class method](http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html)。例如,你需要一張有2張照片的食物,爲什麼只有一張照片,因爲你只用了一次'@ food.photos.build',如果你想要更多,可以這樣做:'n.times {@ food.photos .build}'。你可以查看這個[Nested form](http://railscasts.com/episodes/196-nested-model-form-part-1)瞭解更多信息。 – Thanh

回答

0

如果定義has_many協會:

has_many :images 

has_many協會將添加一些方法,幫助你建立和創建對象:

collection.build(attributes = {}, …) 
collection.create(attributes = {}) 

collection這裏是images。你可以在這裏閱讀更多has_many

而當你定義has_one協會:

has_one :image 

has_one協會將添加一些方法,幫助你建立和創建對象:

build_association(attributes = {}) 
create_association(attributes = {}) 

create_association這裏是image。你可以在這裏閱讀更多has_one

因此,它將有不同的方式創建與has_manyhas_one關聯的新對象。

+0

thx男人,你是一個偉大的幫助..真的很感激它。 –

相關問題