我有 2 个型号。Report
and Server
具有belongs_to 和has_many 关系。我使用创建了一个访问器方法delegate
这允许Report
来查找其关联的Server.company_id
。现在,我想运行一个查询Report
这让我可以找到所有Report
与特定的Server
具有特定的company_id
属性5.
这是我的两个模型。是的,我知道当前的查询不会工作,因为Report
没有属性company_id
.
不,我不想存储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
您可以执行如下查询:
Report.joins(:servers).where(:servers => {:company_id => 5})
对我来说,这是原始 SQL 的更清晰的解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)