如何在2个模型之间创建3列连接表

时间:2014-05-28 22:09:46

标签: ruby-on-rails join activemodel database-relations

我正在尝试在2个具有3列的模型之间创建连接表。这些模型称为UserDare。连接表称为DaresUsers。我希望在联接表中包含author_idaccepter_iddare_id

每个敢于只有一个作者,但会有很多accepters,因为不止一个用户可以接受相同的胆量。我应该使用has_many through关系,如果是这样,我会在模型中声明什么?我在这里的困惑是因为联接表在两个方面引用了User模型:author_idaccepter_id

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

试试这个:

class Dare < ActiveRecord::Base
  belongs_to :author, class_name: 'User'
  has_many :dare_user_relations, dependent: :destroy
  has_many :accepters, through: :dare_user_relations
end

class DareUserRelation < ActiveRecord::Base
  belongs_to :accepter, class_name: 'User'
  belongs_to :dare
end

class User < ActiveRecord::Base
  has_one :dare, foreign_key: 'author_id', dependent: :destroy
  has_many :dare_user_relations, dependent: :destroy
  has_many :dares, through: :dare_user_relations, foreign_key: 'accepter_id'
end

或没有模特:

class Dare < ActiveRecord::Base
  belongs_to :author, class_name: 'User'
  has_and_belongs_to_many :accepters, class_name: 'User', association_foreign_key: 'accepter_id'
end

class User < ActiveRecord::Base
  has_one :dare, foreign_key: 'author_id', dependent: :destroy
  has_and_belongs_to_many :dares, foreign_key: 'accepter_id'
end