我有以下型号:
class Assembly < ActiveRecord::Base
has_many :manifests
has_many :parts, :through => :manifests
end
class Manifest < ActiveRecord::Base
belongs_to :assembly
belongs_to :part
end
class Part < ActiveRecord::Base
has_many :manifests
has_many :assemblies, :through => :manifests
end
manifests
包含的位置:
assembly_id
part_id
field1
field2
...
如何使用habtm更新其他字段(field1
,field2
...)?
答案 0 :(得分:1)
根据http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many,您必须使用has_many-through而不是habtm关系(就像您在问题中所做的那样)。然后,您可以简单地使用此代码来设置零件和装配体之间的关系:
#create assembly
ass1 = Assembly.new
ass1.save!
# create part
part_x = Part.new
part_x.save!
# create relationship between assembly and part using the join model Manifest
Manifest.new(assembly: ass1, part: part_x, field1: 1, field2: "test").save!