2009-09-17 33 views
0

我的模型看起來像這樣(舉例):的ActiveRecord和裝載數據

class Bank < ActiveRecord::Base 
    has_and_belongs_to_many :currencies 
    # other stuff 
end 

當我想從數據庫的一些銀行我做的:

bank = Bank.first :joins => :some_table, 
     :conditions => { 
      #some conditions 
     } 

現在,有沒有的明確方式從數據庫檢索所提供條件的貨幣並按某種順序對其進行排序並將其存儲在bank.currencies

我在做這樣的事情:

bank.currencies.reject! { |c| c.value < something } 
bank.currencies.sort! { |x,y| x.value <=> y.value } 

它的工作原理,但這種方式我檢索所有的記錄,根據自己的過濾。 我想讓DBMS爲我做。

這只是銀行和貨幣的一個例子。我有一些大的記錄,我認爲重要的是找回那些讓我感興趣的人。

回答

1

可以發出「找到」的關係的條款,這樣的:如果你

bank.currencies.find(:all, :conditions => {something}, :order => {something}) 

,或者更喜歡:

bank.currencies.all(:conditions => {something}, :order => {something}) 

所有的標準ActiveRecord選項應該可用 - 例如限制,訂單等

當然,如果你發現自己重複使用的查詢邏輯,你可以在貨幣模型聲明命名範圍 - 比如「with_count_greater_than」和「in_order」 - 然後把它們連在一起:

bank.currencies.with_count_greater_than(10).in_order 

您可能還需要調查SearchLogic,它實現了許多有用的命名範圍爲您服務。

1

也許這對你有幫助嗎?

bank = Bank.first 
concurrencies = Concurrency.find(:all, :conditions => {:bank => bank}, :order => "position desc") 

或者你可以改變你的銀行模式

def Bank << AR 
    has_many :concurrencies 

    def ordered_concurrencies 
    Concurrency.for_bank(self) 
    end 
end 

def Concurrency << AR 
    belongs_to :bank 

    named_scope :for_bank, lambda { |*args| {:conditions => {:bank => args.first}, :order => "position desc"} } 
end 

所以,你可以調用

Bank.first.ordered_concurrencies 

,並得到有序併發性的ActiveRecord的收集。

在這旁邊,這個解決方案,您可以添加其他條件,以及:

Bank.first.ordered_concurrencies.find(:all, :conditions => ["name like ?", "Dollar"])