2012-01-19 102 views
0

的方法,我有兩個型號:創建關聯對象

class User < ActiveRecord::Base 
    has_many :accounts 
end 

class Account < ActiveRecord::Base 
    belongs_to :user 
end 

我希望能夠通過基於實例方法的一些標準到我的賬戶排序。這是我想用這個方法:

def sorted 
    partition { |account| account.is_referral?}.each do |a| 
    a.sort! {|a,b| a.label <=> b.label} 
    end.flatten 
end 

其中is_referral?labelAccount類的兩個實例方法。

因此,我可以通過User.first.accounts.sorted獲得排序賬戶。

我能夠做到這一點,如果我創建了一個範圍,做的東西,然後擴展它:

scope :filtered, lambda { |filter| 
    if filter == Listing::FILTER_INACTIVE 
     where("status = ?", Account::STATUS_INACTIVE) 
    elsif filter == Account::FILTER_ACTIVE 
     where("status = ?", Account::STATUS_ACTIVE)  
    end 
    } do 
    def sorted 
     partition { |account| account.is_referral?}.each do |a| 
     a.sort! {|a,b| a.label <=> b.label} 
     end.flatten 
    end 
    end 

現在我可以用User.accounts.filtered(Account::FILTER_ACTIVE).sorted。我想這是因爲scope.class返回ActiveRecord::RelationUser.first.accounts.class返回Array

我也試過這樣:

scope :sorted, lambda { |object| 
    object.partition { |account| account.is_referral?}.each do |a| 
    a.sort! {|a,b| a.label <=> b.label} 
    end.flatten 
} 

但是,這將引發NoMethodErrornil.partition

任何幫助表示讚賞。

回答

1

您可以通過執行

class User < ActiveRecord::Base 
    has_many :accounts do 
    def sorted 
     proxy_target.partition { |account| account.is_referral?}.each do |a| 
      a.sort! {|a,b| a.label <=> b.label} 
     end.flatten 
    end 
    end 
end 

定義上的關聯代理方法見http://guides.rubyonrails.org/association_basics.html#association-extensions

使用此與User.last.accounts(true).sorted得到的結果,否則你的公會將不會被加載,並且您會收到空數組結果。

+0

感謝您的想法,但我得到空數組作爲結果。確切的實現是'has_many:accounts,:through =>:calendars',但無論我在哪裏定義方法(在'Calendar'或'User'中),我都會得到空數組。 – shime

+0

我發現了爲什麼我得到這個,並添加解釋到您的文章。再次感謝。 – shime

相關問題