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

时间:2016-05-24 16:53:32

标签: ruby-on-rails activerecord associations

让我们说,我有三种型号。

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

现在我可以创建像:

这样的关联
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])

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

2 个答案:

答案 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