2009-09-17 64 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"])