我有2个型号 . Report
和 Server
具有belongs_to和has_many关系 . 我使用 delegate
创建了一个访问器方法,允许 Report
找到其关联的 Server.company_id
. 现在,我想在 Report
上运行一个查询,它允许我查找与特定 Server
相关联的所有 Report
,该特定 Server
具有5的特定 company_id
属性 .
这是我的两个模特 . 是的,我知道当前的查询不起作用,因为 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
4 回答
Server.where(company_id:5).first.reports
这应该可以解决问题
你也可以这样添加一个范围
然后写
您可以执行以下查询:
对我来说,这是原始SQL的更清晰的解决方案 .
我正在使用Rails 4.1.7,并且接受的答案对我不起作用 . 做了什么工作
请注意,区别在于where子句是多元化的键(:服务器而不是:server)