【问题标题】:Rails 5 Query when using both single and multiple association relationships使用单个和多个关联关系时的Rails 5 Query
【发布时间】:2023-03-25 01:50:01
【问题描述】:

我有一个具有以下设置的 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

我要做的是编写一个 Rails 5 查询,以便它返回设置了特定汽车属性的所有组织,即返回所有用户拥有给定品牌汽车的组织。

查询时如何加入Organization上的Car类?目前,我通过执行以下操作根据用户条件搜索组织:

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

但我也希望能够将汽车条件添加到查询中。

【问题讨论】:

    标签: mysql ruby-on-rails rails-activerecord ruby-on-rails-5 active-record-query


    【解决方案1】:

    用这个怎么样-

    ###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 控制台上使用它..进行一些适合您的关联的更改。如果它有帮助,请告诉我。
    • 我无法直接使用它,因为当我这样做时,我收到一条错误消息:“Association named cars not available on organizations”。所以我所做的就是将该范围添加到 User 模型中,获取具有该汽车品牌的用户 ID 数组,然后在组织的查询中使用该数组。这确实给了我想要的结果,但确实需要多次查询。
    • 嗯是的..因为这取决于您的模型关联...,现在您要处理三个模型..第一个用户和汽车,然后使用它来查询组织。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2014-12-24
    • 1970-01-01
    相关资源
    最近更新 更多