2014-06-18 129 views
0

這裏是我與工作對象:有沒有更好的方法在班級上找到關聯?

class Client < ActiveRecord::Base 
    has_many :servers 

    def self.active 
    where("updated_at > ?", 1.month.ago) 
    end 
end 

class Server 
    belongs_to :client 
end 

我希望能夠得到屬於活躍客戶,像這樣的所有服務器:

Client.active.servers 

唯一的辦法我能想到的要做到這一點是:

def Client.servers 
    Server.where(id: all.collect(&:id)) 
end 

必須有更多的Rails-y做到這一點!

回答

1

我相信我已經找到你要找的內容,它的活動記錄方法merge

Server.joins(:client).merge(Client.active) 

在測試中,如果你發現你的updated_at列衝突,一定要消除歧義它在你active範圍:

def self.active 
    where("clients.updated_at > ?", 1.month.ago) 
end 
1

你想從服務器加入到客戶端。像這樣的東西應該工作:

Server.joins(:client).where('clients.updated_at > ?', 1.month.ago)

+0

但我希望能夠用在類中定義的查詢方法客戶。如果我這樣做,我要麼違反DRY或封裝(通過在服務器上定義它們)。 – muirbot

+0

這麼違反它們。他們只是指導方針。這是基於連接表中的屬性來查詢服務器的方式。另一種選擇是從客戶端到服務器的一些鈍的flat_map。 –

相關問題