Rails: 3个表之间的循环多对多关系

Rails: circular Many to Many relation between 3 tables

比方说,我有三个模型。

现在我可以像这样创建关联:

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

有没有更好的解决办法?我应该修改关联还是这样?

是的,因为你有答案的用户外键,你可以简单地做:

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

如果您需要用户能够创建带有问题的调查并从粗略的界面预设答案,那么这些关系将无法解决问题。如果你想生成指标——比如说最常见的答案,它也不是很理想。

而是考虑使用单独的表格来获取答案 "presets" 以及回答问题者提交的回复。

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