【问题标题】:Rails: circular Many to Many relation between 3 tablesRails:3个表之间的循环多对多关系
【发布时间】:2016-05-24 16:53:31
【问题描述】:

假设,我有三个模型。

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

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

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

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

【问题讨论】:

  • 取决于,用户总是写自己的答案还是应该有预设选项?您是否需要用户界面供用户创建问题?
  • @max,是的,用户有一个用于创建/更新他们的问题的界面。此外,他们可以回答自己的问题。
  • 您的解决方案在我看来是最佳的。您对此有任何顾虑吗?

标签: ruby-on-rails activerecord associations


【解决方案1】:

如果您需要用户能够创建带有问题和预设答案的调查,那么这些关系就不会削减它。如果您想生成指标,它也不是很理想 - 比如说最常见的答案。

请考虑为答案“预设”和回答问题的人提交的回复使用单独的表格。

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

【讨论】:

    【解决方案2】:

    是的,因为您在答案上有用户外键,您可以简单地这样做:

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

    【讨论】:

    • 是的,这是一种方式。但这是该场景的最佳解决方案吗? (+1)
    • “最佳解决方案”是主观的,难以证明,但对于指定的模型关系,很难想象比这更简单的东西——它只是对两个参数的单表查询,这两个参数结果需要。您问题中的示例将起作用,但更复杂并且涉及不必要的连接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    相关资源
    最近更新 更多