0

我有以下設置一個Rails應用程序:Rails的5查詢使用單個和多個關聯關係時

class Organization < ApplicationRecord 
    has_many :user_orgs 
    has_many :users, :through => :user_orgs 
end 

class UserOrg < ApplicationRecord 
    # organization_id  :integer 
    # user_id :integer 
    belongs_to :organization 
    belongs_to :user 
end 

class User < ApplicationRecord 
    # car_id :integer 
    has_many :user_orgs 
    has_many :organizations, :through => :user_orgs 
    belongs_to :car 
end 

class Car < ApplicationRecord 
    # brand :string 
    has_many :users 
end 

我所試圖做的是寫一個Rails 5查詢,以便它返回所有組織在那裏設置了某個汽車屬性,即返回所有組織,其中有一個擁有給定品牌汽車的用戶。

如何在進行查詢時加入本組織的Car類?目前,我搜索的組織基於用戶標準做到以下幾點:

Organization.joins(:users).where("users.name = ?", name) 

但我想能夠添加汽車標準的查詢以及。

回答

0

如何使用這個 -

###add this scope in Organisation model that has - has_many :users 
scope :get_users_by_carBrand, -> (brand) { includes(:cars).where(:cars=> {:name => brand} } 

###this is the select query 
Organization.includes(:users).get_users_by_carBrand("BMW") 
+0

這看起來像它只會搜索用戶給定的名稱,而不是一個給定名稱的車嗎? – Hawkeye001

+0

我已經更新了我的答案...請檢查 – Milind

+0

對不起@milind,我在我的問題中出現錯誤(汽車/用戶關聯被顛倒;現在在原始摘要中修復),所以根據實際結構,解決方案wouldn不適用。 – Hawkeye001