ddig
ddig

Reputation: 13

How to Create a 3 Column Join Table Between 2 Models

I'm trying to create a join table between 2 models that has 3 columns. The models are called User and Dare. The join table is called DaresUsers. And what I want to include in the join table is an author_id, accepter_id, dare_id.

Each dare will only have one author but will have many accepters because more than one user can accept the same dare. Should I use a has_many through relationship and if so what would I declare in my models? My confusion here is because the User model is referenced by the join table in two respects: the author_id and accepter_id.

Thanks for any help!

Upvotes: 1

Views: 664

Answers (1)

Sergey Alekseev
Sergey Alekseev

Reputation: 12310

Try this:

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

or w/o a model:

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

Upvotes: 2

Related Questions