2011-11-16 44 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

相关问题