简体   繁体   English

Rails 4 HABTM has_many:through

[英]Rails 4 HABTM has_many :through

Team, looking for some help for a very specific (newbie) situation on a Rails 4 association. 团队,在Rails 4协会上针对特定情况(新手)寻求帮助。 We have 3 models: 我们有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

This configuration works well when trying to check for Products under specific Brand (or Line ) and viceversa: different Brands (or Lines ) available for a specific Product . 尝试检查时,此配置运作良好Products在特定Brand (或Line不同:),反之亦然Brands (或Lines ),可用于特定的Product However, when it comes to delete/destroy there is an issue. 但是,在删除/销毁方面存在问题。 We are getting this Rspec error: 我们收到此Rspec错误:

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

We have made research on this exception, checked for Rails API, with no luck, examples found are showing a different model configuration. 我们已经对此异常进行了研究,检查了Rails API,但没有走运,发现的示例显示了不同的模型配置。 What's missing on this approach? 这种方法缺少什么?

Appreciate your help guys! 感谢您的帮助!

In my opinion, it should be something like this: 我认为应该是这样的:

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

And in migrations: 在迁移中:

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

I hope it will help. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM