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

대신 제품 양식을 사용하는 것이 더 합리적입니까? 따라서 제품 색인 작업을 사용하여 모든 제품을 나열 할 수 있습니다. 그런 다음 Product 양식을 사용하여 fields_for 태그를 통해 여러 Costs를 처리하고 Product 모델의 accepts_nested_attributes_for : 비용을 처리 할 수 ​​있습니다.

편집 : 그럼이 종류의 모델을보고 계십니까?

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

답장을 보내 주셔서 감사합니다. 나는 언급했던 것과 같은 유형의 협회를했다. 두 가지 상황으로 비용과 제품이 만들어지기 때문에 제품 속성을 저장하는 동안 제품 비용을받을 수 없습니다. 관리자가 제품을 생성합니다. 모든 제품을 모든 고객이 사용할 수있게 된 후. 그러나 각 고객은 모든 제품에 대해 자체 비용을 설정해야합니다. 비용은 고객에 따라 다를 수 있습니다. 비용 테이블에 연관된 customer_id 및 product_id가 있습니다. – nishanthan

관련 문제