Ruby-on-rails Rails:基于关联值的 ActiveRecord 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19489017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:54:15  来源:igfitidea点击:

Rails: ActiveRecord query based on association value

ruby-on-railsrubyactiverecordassociations

提问by user2158382

I have 2 models. Reportand Serverthat have a belongs_to and has_many relationship. I created an accessor method using delegatethat allows a Reportto find its associated Server.company_id. Now, I want to run a query on Reportthat allows me to find all Reportthat are associated with a specific Serverthat has a specific company_idattribute of 5.

我有2个模型。Report并且Server有一个belongs_to 和has_many 关系。我创建了一个访问器方法delegate,它允许 aReport找到其关联的Server.company_id. 现在,我想运行一个查询Report,让我可以找到ReportServer具有特定company_id属性 5的特定关联的所有内容。

Here are my two models. And yes I know the current query wont work since Reportdoes not have an attribute company_id.

这是我的两个模型。是的,我知道当前查询不起作用,因为Report没有属性company_id

And no, I dont want to store company_idinside of Reportsince that information doesn't belong in Report.

不,我不想存储company_id在里面,Report因为该信息不属于Report.

Report

报告

class Report < ActiveRecord::Base

 belongs_to :server

 delegate :company_id, :to => :server

    class << self

        def method(url, base_url)
            #Report.where(company_id: 5)
        end
    end

end

Server

服务器

class Server < ActiveRecord::Base

 attr_accessible :company_id

 has_many :reports

end

回答by KappaNossi

You can perform a query like this:

您可以执行如下查询:

Report.joins(:servers).where(:servers => {:company_id => 5})

To me, this is the cleaner solution to raw SQL.

对我来说,这是原始 SQL 的更干净的解决方案。

回答by Joseph Gill

I'm using Rails 4.1.7 and the accepted answer did not work for me. What did work is

我正在使用 Rails 4.1.7,但接受的答案对我不起作用。什么工作是

Report.joins(:server).where(:servers => {:company_id => 5})

Note that the difference is the key in the where clause is pluralized (:servers instead of :server)

请注意,区别在于 where 子句中的关键是复数形式(:servers 而不是 :server)

回答by Patrick Oscity

This should do the trick

这应该可以解决问题

Report.joins(:server).where('servers.company_id = ?', 5)

you could also add a scope for this like so

你也可以像这样添加一个范围

scope :with_company_id, lambda {|id| joins(:server).where('servers.company_id = ?', id) }

and then write

然后写

Report.with_company_id(5)

回答by nroose

Server.where(company_id: 5).first.reports

Server.where(company_id: 5).first.reports