Rails:基于关联值的 ActiveRecord 查询 [英] Rails: ActiveRecord query based on association value

查看:33
本文介绍了Rails:基于关联值的 ActiveRecord 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个模型.ReportServer 具有belongs_to 和has_many 关系.我使用 delegate 创建了一个访问器方法,它允许 Report 找到其关联的 Server.company_id.现在,我想对 Report 运行一个查询,它允许我找到与具有特定 Server 的特定 Server 相关联的所有 Reportcode>company_id 属性为 5.

I have 2 models. Report and Server that have a belongs_to and has_many relationship. I created an accessor method using delegate that allows a Report to find its associated Server.company_id. Now, I want to run a query on Report that allows me to find all Report that are associated with a specific Server that has a specific company_id attribute of 5.

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

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

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

And no, I dont want to store company_id inside of Report since that information doesn't belong in 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

服务器

class Server < ActiveRecord::Base

 attr_accessible :company_id

 has_many :reports

end

推荐答案

您可以执行如下查询:

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

对我来说,这是原始 SQL 的更简洁的解决方案.

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

这篇关于Rails:基于关联值的 ActiveRecord 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆