2012-01-19 2 views
0

하는 방법을 만드는. 이것은 내가이 사용하고자하는 방법입니다 : is_referral?labelAccount 클래스의 두 인스턴스 메소드는내가 두 가지 모델이 연관된 객체

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

.

따라서 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.classActiveRecord::Relation이고 이 Array 인 결과라고 생각합니다.

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

하지만이 nil.partition에 대한 NoMethodError 발생 :

나는이 일을 시도했습니다.

도움을 주시면 감사하겠습니다.

답변

1

당신은 그렇지 않으면 협회가로드되지 않기 때문에, 결과를 얻을 수 User.last.accounts(true).sorted와 사용을 http://guides.rubyonrails.org/association_basics.html#association-extensions

를 참조

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 

을 수행하여이 문제를 협회에 프록시 방법을 정의 할 수 있습니다 당신은 빈 배열을 받게됩니다 결과.

+0

아이디어를 주셔서 감사합니다. 그러나 결과적으로 빈 배열이 나타납니다. 정확한 realtion은'has_many : accounts, : through => : calendars'이지만, 당신의 메소드를 정의 할 때 (Calendar 또는 User에서) 빈 배열을 얻습니다. – shime

+0

나는 왜 이것을 얻었고 귀하의 게시물에 설명을 추가했는지 발견했습니다. 다시 한번 감사합니다. – shime

관련 문제