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?
created_by_id
? - Manoj Mongacreated_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 byuser_instance.created_question_association
- Manoj Monga