3
votes

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?

1
How are you trying to add the created_by_id? - Manoj Monga
I think that may be my problem....I don't know how to add the created_by_id... - Neil Hoff
The created_by_id will be added while the question is being created. So in your controller you can try something like @question = current_user.questions_created.new(params[:question]) and then save it by @question.save. Or whatever logic are you using, you just need to call the question by user_instance.created_question_association - Manoj Monga

1 Answers

3
votes

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