问题
So I have 3 models..
A User model, a Questions model and an Answer model.
A user has_many questions, and questions belong_to user
A question has_one answer, and the answers belong_to the question.
Now I've created default seed questions that apply to all users i.e. @questions = Question.all
And these same questions every user can see, now how can I allow each user to write their own answer to these questions when they aren't directly associated with the question?
I.e. u.questions.answer returns answer is undefined.
回答1:
I recommend a has many through association, with a link to the answer in the intermediate table. Thus:
class User < ActiveRecord::Base
has_many :user_questions
has_many :questions, through: :user_questions
end
class UserQuestion < ActiveRecord::Base
belongs_to :user
belongs_to :question
belongs_to :answer
end
In this way, you can create questions that you can associate with a user or not, and also link to their answer, where it exists.
来源:https://stackoverflow.com/questions/20338551/tricky-questions-answers-associations