的方法,我有兩個型號:創建關聯對象
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?
和label
是Account
類的兩個實例方法。
因此,我可以通過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::Relation
和User.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
}
但是,這將引發NoMethodError
的nil.partition
。
任何幫助表示讚賞。
感謝您的想法,但我得到空數組作爲結果。確切的實現是'has_many:accounts,:through =>:calendars',但無論我在哪裏定義方法(在'Calendar'或'User'中),我都會得到空數組。 – shime
我發現了爲什麼我得到這個,並添加解釋到您的文章。再次感謝。 – shime