导轨:3个表之间的圆形多对多关系



假设,我有三个模型。

  • 用户(可以发布许多问题)
  • 问题(可以有很多答案)
  • 答案
  • (用户可以发布许多答案

现在我可以创建如下关联:

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])

有没有更好的解决方案?我应该修改关联还是修改方式?

如果您需要用户能够从 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

是的,因为您在答案上有用户外键,您可以简单地执行以下操作:

@answers = Answer.where(user_id: params[:id], question_id: params[:question_id])

最新更新