1

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!

ekremkaraca
  • 1,453
  • 2
  • 18
  • 37
ddig
  • 13
  • 3

1 Answers1

2

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
Sergey Alekseev
  • 11,910
  • 11
  • 38
  • 53
  • thanks for your response, the problem with this solution though is that now the `user` can only have one `dare`, when they should be able to have many `dares`. Also, the `user` should `has_and_belongs_to_many` `dares` with a `foreign_key: 'accepter_id'` correct? – ddig May 28 '14 at 23:03
  • @ddig, thanks for details, got your case. See the updated answer. – Sergey Alekseev May 29 '14 at 12:58
  • I think this works thank you very much, I just have one last question, I was under the impression that whenever you have two `has_and_belongs_to_many` relationships between two models that a join table is always necessary. I'm referencing you're second solution, specifically the relationship between `accepters` and `dares` – ddig May 30 '14 at 14:44
  • Sure, you need a join table named dares_users. However, keep in mind that you don't need a model for this join table. Let me know if you have other questions. – Sergey Alekseev May 30 '14 at 14:54
  • yes Sergey this helped me, I ended up creating a new model because I needed the join table to have multiple attribute columns, thank you very much! – ddig Jun 03 '14 at 04:13