Rails 3.1,has_many:through,habtm

时间:2012-01-21 19:00:38

标签: ruby-on-rails

我有以下型号:

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更新其他字段(field1field2 ...)?

1 个答案:

答案 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!