2011-11-16 69 views
0

我有我的數據庫中的成本和產品表,我想要以成本的形式獲得所有產品的成本,然後將所有product_id,成本值保存到成本表中。如何創建一個form_for多個記錄

我的模型

class Cost < ActiveRecord 
    belongs_to :test 
end 

class Product < ActiveRecord 
    has_many :costs 
end 

在這裏,我不知道更好的方法,使形式的參數,並保存在表中的記錄。請幫我

回答

1

我會從你的關聯開始 - 是這樣的:測試關聯應該是:產品?

http://guides.rubyonrails.org/association_basics.html

看一看部分2.3的has_many協會。

class Cost < ActiveRecord 
belongs_to :product 
end 

class Product < ActiveRecord 
has_many :costs 

accepts_nested_attributes_for :costs, :reject_if => :all_blank, :allow_destroy => true 
end 

改爲使用產品形式會更有意義嗎?因此,產品索引操作只能用於列出所有產品。然後,產品表單可以用於通過產品模型中的fields_for標記和accepting_nested_attributes_for:cost來處理多個成本。

編輯: 那麼繼續你的評論,你正在尋找這種模型?

class Customer < ActiveRecord 
    has_many :costs 
    has_many :products, :through => :costs 

    accepts_nested_attributes_for :costs, :reject_if => :all_blank, :allow_destroy => true 
end 

class Cost < ActiveRecord 
    belongs_to :customer 
    belongs_to :product 
end 

class Product < ActiveRecord 
    has_many :costs 
    has_many :customers, :through => :costs 

    accepts_nested_attributes_for :costs, :reject_if => :all_blank, :allow_destroy => true 
end 
+0

感謝您的回覆。我和你提到過的那種類型的聯繫。 這裏我不能在保存產品屬性的同時獲取產品的成本,因爲成本和產品是在兩種不同的情況下創建的。 產品由admin用戶創建。之後,所有產品均可供所有客戶使用。 但每個客戶都必須爲所有產品設置自己的成本。成本可能會因顧客而異。 成本表中的customer_id和product_id與其關聯。 – nishanthan

相關問題