让我们说,我有三种型号。
现在我可以创建像:
这样的关联class User < ActiveRecord::Base
has_many :questions
has_many :answers
end
class Question < ActiveRecord::Base
belongs_to :user
has_many :answers
end
class Answer < ActiveRecord::Base
belongs_to :user
belongs_to :question
end
现在,如果我这样做,那么为特定问题查询找到任何用户的答案将是:
@answers = User.find(params[:id]).answers.where(:question_id => params[:question_id])
有没有更好的解决方案?我应该修改关联还是这样?
答案 0 :(得分:1)
是的,因为你有答案的用户外键,你可以这样做:
@answers = Answer.where(user_id: params[:id], question_id: params[:question_id])
答案 1 :(得分:1)
如果您需要用户能够使用问题创建调查并从crud界面预设答案,那么这些关系就不会削减它。如果你想生成指标,它也不是最优的 - 比如说最常见的答案。
相反,请考虑使用单独的表格来回答“预设”以及回答问题的人提交的回复。
class User < ActiveRecord::Base
has_many :questions
has_many :replies
has_many :selected_answers, through: :replies,
source: :answer
has_many :answered_questions, through: :replies,
source: :question
end
class Question < ActiveRecord::Base
belongs_to :user
has_many :answers
has_many :replies, through: :answers
end
# this is a "preset"
class Answer < ActiveRecord::Base
belongs_to :question
has_many :replies
end
# this is the answer checked by a user
class Reply < ActiveRecord::Base
belongs_to :user
belongs_to :answer
has_one :question, through: :answer
end