如果以及如何在ActiveRecord中使用has_and_belongs_to_many关联

时间:2018-06-14 01:10:04

标签: ruby activerecord model-associations

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

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

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

1 个答案:

答案 0 :(得分:0)


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

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

快乐的编码!