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

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

问题描述

我有2个型号。 报告服务器有一个belongs_to的和的has_many关系。我创建使用代理的存取方法,它允许报告找到与其相关的 Server.company_id 。现在,我要运行,让我找到报告查询所有的报告与某个特定的关联服务器具有特定的company_id 5的属性。

下面是我的两个型号。是的,我知道目前的查询不会工作,因为报告不具有的属性的company_id

不,我不想存储的company_id 报告的内部,因为这些信息不属于中的报告

报告

 类报告<的ActiveRecord :: Base的

 belongs_to的:服务器

 代表:的company_id,:以=> :服务器

    类<<自

        高清方法(URL,BASE_URL)
            #Report.where(的company_id:5)
        结束
    结束

结束
 

服务器

 类服务器16;的ActiveRecord :: Base的

 attr_accessible:的company_id

 的has_many:报告

结束
 

解决方案

您可以做一个查询这样的:

  Report.joins(:服务器)。凡(:服务器=> {:的company_id => 5})。全部
 

对我来说,这是清洁的解决方案,以原始的SQL。

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.

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

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

解决方案

You can do a query like this:

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

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

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

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