Tricky Questions Answers associations? [closed]

心已入冬 提交于 2019-12-20 03:12:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!