簡體   English   中英

Rails查詢具有has_many和belongs_to關系的模型

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM