[英]Rails query for models having has_many and belongs_to relationship
我是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'的所有响应部分。 我尝试了几种方法,但无法成功查询。 有人可以说出进行这种查询的方法。 提前致谢。
尝试:
Question.where(qtype: 'mobile').collect(&:response_parts)
这将为您提供所有带有qtype = 'mobile'
的questions
所有response_parts
更新:(避免N + 1个查询)
Question.where(qtype: 'mobile').collect(&:response_parts)
这将对每个导致“ N + 1”个查询的question
每个response_parts
执行一个选择查询。
为了避免“ N + 1个查询”,即一个查询来检索问题, n
查询来检索resposne_parts
,您可以添加includes(:join_relation)
(其中:join_relation
在您的情况下是response_parts
),如下所示:
Question.includes(:response_parts).where(qtype: 'mobile').collect(&:response_parts)
尝试这个
Question.where(qtype: "mobile").first.response_parts
您可以包括两个模型之间的关系并对其添加约束:
ResponsePart.includes(:question).where(questions: { qtype: 'mobile' })
这将从数据库中检索出所有与“ qtype == 'mobile'
“匹配的问题的ResponsePart对象。
这也是检索这些记录的最有效方法。
Question.where(qtype: 'mobile').collect(&:response_parts)
这将查询数据库,以获取每个具有“ qtype == 'mobile'
“的问题的相应response_parts 示例:如果您有6个带有” qtype == 'mobile'
“的问题,它将为每个Question创建6个SQL查询。
Question.where(qtype: "mobile").first.response_parts
这只是检索与第一个与条件“ qtype == 'mobile'
“相匹配的问题有关的ResponsePart对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.