Rails查询具有has_many和belongs_to关系的模型

时间:2013-12-24 16:14:02

标签: ruby-on-rails ruby-on-rails-4

我对rails很新。我有以下型号

class Question < ActiveRecord::Base
  has_many :options
  has_many :response_parts
end

class ResponsePart < ActiveRecord::Base
  belongs_to :question
end

相应的支架

rails g scaffold Question qorder:string qtext:text qtype:string

rails g scaffold ResponsePart answer:string question:belongs_to

现在我想要qtype为'mobile'的所有响应部分。我尝试过几种方法,但无法成功查询。有人可以告诉你这样的查询方式。提前谢谢。

3 个答案:

答案 0 :(得分:0)

尝试:

Question.where(qtype: 'mobile').collect(&:response_parts)

这将为所有response_parts questions提供qtype = 'mobile'

更新:(避免N + 1次查询)

Question.where(qtype: 'mobile').collect(&:response_parts)

这会对每个response_parts执行一个选择查询,每个question会导致&#34; N + 1&#34;查询。

为了避免&#34; N + 1查询&#34;例如,一个用于检索问题的查询和用于检索n的{​​{1}}个查询,您可以添加resposne_parts(在您的案例中includes(:join_relation):join_relation),如下所示:< / p>

response_parts

答案 1 :(得分:0)

试试这个

Question.where(qtype: "mobile").first.response_parts

答案 2 :(得分:0)

您可以包含两个模型之间的关系并在其上添加约束:

ResponsePart.includes(:question).where(questions: { qtype: 'mobile' })

这将从DB中检索所有与“qtype == 'mobile'”匹配的问题的ResponsePart对象

这也是检索这些记录的最有效方法。


Question.where(qtype: 'mobile').collect(&:response_parts)

这将查询数据库以获取具有“qtype == 'mobile'”的每个问题的相应response_parts 示例:如果您有6个问题“qtype == 'mobile'”,它将为每个问题创建6个SQL查询。

Question.where(qtype: "mobile").first.response_parts

这只是检索与符合条件“qtype == 'mobile'”的第一个问题相关的ResponsePart对象