简体   繁体   中英

Rails query for models having has_many and belongs_to relationship

I am fairly new to 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'. 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'

Update: (Avoiding N+1 queries)

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.

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:

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' "

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.

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

This just retrieves the ResponsePart objects related to the first question matching the condition " qtype == 'mobile' "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM