首页 > 解决方案 > 如果以及如何在 ActiveRecord 中使用 has_and_belongs_to_many 关联

问题描述

尝试创建一个域,用户可以在其中创建咖啡和混合物列表。一种混合物有许多咖啡,一种咖啡有许多混合物。这是我到目前为止所拥有的:

class User < ActiveRecord::Base
  has_many :roasts
  has_many :blends, :through => :roasts

class Roast < ActiveRecord::Base
  belongs_to :user
  # TODO: associate roasts with blends

class Blend < ActiveRecord::Base
  # TODO: associate blends with roasts

我如何建立这种关系?我需要某种连接表吗?

标签: rubyactiverecordmodel-associations

解决方案



你好!我认为您可以像下面的代码块一样定义关联。

class User < ActiveRecord::Base
  has_many :blend_and_roasts
  has_many :blends, through: :blend_and_roasts
  has_many :roasts, through: :blend_and_roasts

class Roast < ActiveRecord::Base
  has_many :blend_and_roasts
  has_many :blends, through: :blend_and_roasts

class Blend < ActiveRecord::Base
  has_many :blend_and_roasts
  has_many :roasts, through: :blend_and_roasts

快乐编码!


推荐阅读