Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql Rails 5在同时使用单个和多个关联关系时进行查询_Mysql_Ruby On Rails_Rails Activerecord_Ruby On Rails 5_Active Record Query - Fatal编程技术网

Mysql Rails 5在同时使用单个和多个关联关系时进行查询

Mysql Rails 5在同时使用单个和多个关联关系时进行查询,mysql,ruby-on-rails,rails-activerecord,ruby-on-rails-5,active-record-query,Mysql,Ruby On Rails,Rails Activerecord,Ruby On Rails 5,Active Record Query,我有一个rails应用程序,具有以下设置: class Organization < ApplicationRecord has_many :user_orgs has_many :users, :through => :user_orgs end class UserOrg < ApplicationRecord # organization_id :integer # user_id :integer belongs_

我有一个rails应用程序,具有以下设置:

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
但是我也希望能够将car条件添加到查询中。

使用这个如何-

###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")

看起来它只会搜索具有给定名称的用户,而不会搜索具有给定名称的汽车?抱歉@milind,我的问题中有一个错误(汽车/用户关联已被颠倒;现在已在原始摘要中修复),因此根据实际结构,该解决方案不适用。没关系。通过添加作用域来检查我的更新答案。首先尝试在rails控制台上使用它。进行一些适合您的关联的更改。请告诉我是否有用。我无法直接使用该解决方案,因为当我这样做时,我收到一个错误,即“组织上没有名为cars的关联”。所以我所做的就是将这个范围添加到用户模型中,得到一个拥有该汽车品牌的用户ID数组,然后在对组织的查询中使用该数组。这确实给了我我想要的结果,但它确实需要多次查询。是的。因为这取决于您的模型关联…,现在您需要处理三个模型。首先是用户和汽车,然后使用它来查询组织。
###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")