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