Rails 4 HABTM has_many:through

时间:2015-07-02 07:19:14

标签: ruby-on-rails ruby ruby-on-rails-4 rspec factory-bot

团队,寻找Rails 4协会非常具体(新手)情况的帮助。 我们有3个型号:

class Brand < ActiveRecord::Base
 has_many :lines, dependent: :destroy
 has_many :products, through: :lines, dependent: :destroy
end

class Line < ActiveRecord::Base
 belongs_to :brand
 has_and_belongs_to_many :products
end

class Product < ActiveRecord::Base
 has_and_belongs_to_many :lines
 has_many :brands, through: :lines
end

尝试在特定Products(或Brand)下检查Line时,此配置效果很好,反之亦然:不同的Brands(或Lines)可用对于特定的Product。但是,当涉及到删除/销毁时,存在一个问题。我们收到此Rspec错误:

ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection:
Cannot modify association 'Brand#products' because the source reflection 
class 'Product' is associated to 'Line' via :has_and_belongs_to_many.

我们对此异常进行了研究,检查了Rails API,没有运气,发现的示例显示了不同的模型配置。这种方法缺少什么?

感谢你们的帮助!

1 个答案:

答案 0 :(得分:0)

在我看来,它应该是这样的:

class Brand < ActiveRecord::Base
 has_many :lines, dependent: :destroy
 has_many :products, through: :lines, dependent: :destroy
end

class Line < ActiveRecord::Base
 belongs_to :brand
 has_and_belongs_to_many :products
end

class Product < ActiveRecord::Base
 belongs_to :brand, through: :line
 has_and_belongs_to_many :lines
end

在迁移中:

create_table :brands , force: true do |t|
  t.string :name
  ...
  t.timestamps null: false    
end

create_table :lines , force: true do |t|
  t.string :name
  t.belongs_to :brand
  ...
  t.timestamps null: false    
end

create_table :products , force: true do |t|
  t.string :name
  ...
  t.timestamps null: false    
end

create_table :line_products, force: true, id: false do |t|
  t.belongs_to :line, index: true
  t.belongs_to :product, index: true
end

我希望它会有所帮助。