[英]Rails query for models having has_many and belongs_to relationship
I am fairly new to rails. 我是Rails的新手。 I have the following models
我有以下型号
class Question < ActiveRecord::Base
has_many :options
has_many :response_parts
end
class ResponsePart < ActiveRecord::Base
belongs_to :question
end
The corresponding scaffolds are 相应的脚手架是
rails g scaffold Question qorder:string qtext:text qtype:string
rails g scaffold ResponsePart answer:string question:belongs_to
Now I want all the response parts where qtype is 'mobile'. 现在我想要qtype为'mobile'的所有响应部分。 I have tried a few ways but could not query successfully.
我尝试了几种方法,但无法成功查询。 Can someone tell a way to make such query.
有人可以说出进行这种查询的方法。 Thanks in advance.
提前致谢。
Try: 尝试:
Question.where(qtype: 'mobile').collect(&:response_parts)
This will give you all the response_parts
for all the questions
with qtype = 'mobile'
这将为您提供所有带有
qtype = 'mobile'
的questions
所有response_parts
Update: (Avoiding N+1 queries) 更新:(避免N + 1个查询)
Question.where(qtype: 'mobile').collect(&:response_parts)
This will execute a select query on each response_parts
for each question
leading to the "N+1" queries. 这将对每个导致“ N + 1”个查询的
question
每个response_parts
执行一个选择查询。
In order to avoid "N+1 queries" ie one Query to retrieve question and n
queries to retrieve resposne_parts
, you can add includes(:join_relation)
(where :join_relation
is response_parts
in your case) as follows: 为了避免“ 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
You can include the relation between the two model and add a constraint on it: 您可以包括两个模型之间的关系并对其添加约束:
ResponsePart.includes(:question).where(questions: { qtype: 'mobile' })
This will retrieve all the ResponsePart objects from the DB having a question which match " qtype == 'mobile'
" 这将从数据库中检索出所有与“
qtype == 'mobile'
“匹配的问题的ResponsePart对象。
This is also the most efficient way to retrieve these records. 这也是检索这些记录的最有效方法。
Question.where(qtype: 'mobile').collect(&:response_parts)
This will query the DB to get the corresponding response_parts of each question having " qtype == 'mobile'
" Example: If you have 6 questions with " qtype == 'mobile'
", it will create 6 SQL queries for each Question. 这将查询数据库,以获取每个具有“
qtype == 'mobile'
“的问题的相应response_parts 示例:如果您有6个带有” qtype == 'mobile'
“的问题,它将为每个Question创建6个SQL查询。
Question.where(qtype: "mobile").first.response_parts
This just retrieves the ResponsePart objects related to the first question matching the condition " qtype == 'mobile'
" 这只是检索与第一个与条件“
qtype == 'mobile'
“相匹配的问题有关的ResponsePart对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.