Neil Hoff
Neil Hoff

Reputation: 2085

Rails: has_many through between two models and also a has_many/belongs to on the same models

I have a has many through relationship to define the questions that a user has answered.

How do to setup a relationship for the questions that a user has created?

Normally you would just create a has_many and belongs_to relationship between users and questions, but since I am also doing a has_many through this will not work.

Here is what I have so far:

Models:

Users
Questions
Answered_questions

User model

has_many :answered_questions
has_many :questions, :through => :answered_questions

Question model:

has_many :answered_questions
has_many :users, :through => :answered_questions

Answered_questions model

belongs_to :question
belongs_to :user

EDIT

I found this answer: https://stackoverflow.com/a/12637532/756623, which led me to try this:

User model addition:

has_many :questions_created, :class_name => "Question", :inverse_of => :created_by

Question model addition:

belongs_to :created_by, :class_name => "User", :foreign_key => "created_by_id", :inverse_of => :questions_created 

I also added the column created_by_id to the Questions table

Now...the user_id is not being added to the created_by_id column.

What do I have wrong?

Upvotes: 3

Views: 2308

Answers (1)

Jesper
Jesper

Reputation: 4555

I think something like this may solve your problem:

# User
has_many :answered_questions
has_many :questions, :through => :answered_questions
has_many :created_questions, class_name: Question, foreign_key: :author_id

# Question
has_many :answered_questions
has_many :users, :through => :answered_questions
belongs_to :author, class_name: User

# Answered questions
belongs_to :question
belongs_to :user

Upvotes: 3

Related Questions