ActiveRecord和从相关表加载数据

时间:2009-09-17 11:05:27

标签: ruby-on-rails ruby

我的模型看起来像这样(例子):

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为我做这件事。

这只是银行和货币的一个例子。我有一些重要的记录,我认为只检索那些我感兴趣的内容非常重要。

2 个答案:

答案 0 :(得分: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-Collection。

除此之外,使用此解决方案还可以添加其他条件:

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

答案 1 :(得分:1)

您可以在关系上发出“find”子句,如下所示:

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

或者,如果您愿意:

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

所有标准的ActiveRecord选项都应该可用 - 例如限制,订单等。

当然,如果您发现自己重新使用查询逻辑,则可以在Currency模型上声明命名范围 - 比如'with_count_greater_than'和'in_order' - 然后将它们链接在一起:

bank.currencies.with_count_greater_than(10).in_order

您可能还想调查SearchLogic,它会为您实现许多有用的命名范围。