2013-02-08 76 views
0

我有了像這樣的關係的產品型號:在rails中,我可以創建一個具有多個關係的產品嗎?

has_many :product_images
has_many :product_specs

的關係都工作正常,我感到高興。

當我創建我的新產品時,我將控制器設置爲在產品創建後保存product_image和product_spec。問題是:我需要多個規格和產品圖像。有沒有辦法在新產品的表單中添加多個product_images和多個product_specs,並在產品創建時一次性創建它們?另外,用戶將決定他們需要添加多少圖片和規格。

我很欣賞任何人的建議。

回答

1

你應該閱讀rubyonrails API更深一點;)link

class Member < ActiveRecord::Base 
    has_many :posts 
    accepts_nested_attributes_for :posts 
end 

現在,您可以設置或通過屬性哈希相關的崗位模型更新屬性。

對於沒有id鍵的每個散列,除非散列還包含一個計算結果爲true的_destroy鍵,否則將新實例化一條新記錄。

params = { :member => { 
    :name => 'joe', :posts_attributes => [ 
    { :title => 'Kari, the awesome Ruby documentation browser!' }, 
    { :title => 'The egalitarian assumption of the modern citizen' }, 
    { :title => '', :_destroy => '1' } # this will be ignored 
    ] 
}} 

member = Member.create(params['member']) 
member.posts.length # => 2 
member.posts.first.title # => 'Kari, the awesome Ruby  documentation browser!' 
member.posts.second.title # => 'The egalitarian assumption of the modern citizen' 
+0

我嘗試,我只是不知道在哪裏看。 :)很好知道屬性散列,這是有道理的。謝謝! – jmcharnes 2013-02-08 19:09:37

+0

是的。表單的實施取決於你。可能會選擇寶石或您的個人實施。 – FUT 2013-02-08 19:12:08

1

我會建議看Ryan Bates的nested form寶石。這正是你正在尋找的。

這裏是link。 它的Railscasts是here

+0

我來看看它,謝謝! – jmcharnes 2013-02-08 18:59:36

相關問題