2010-06-30 3 views
0

여기한 모델의 메서드에서 다른 모델의 메서드로 var를 전달하려면 어떻게해야합니까?

def credit_status_on_create 
    Organization.find(self.organization_id).update_credits 
end 

그리고 여기 내 다른 모델의 내 하나 개의 모델 ..

CardSignup.rb입니다. , 무엇을 수행 할 수 있습니다 : 당신은 내가 여기에 쓴 것은 VAR이 ([ID] PARAMS)에 의해 수행 할 수없는 경우

def update_credits 
    @organization = Organization.find(params[:id]) 
    credit_count = @organization.card_signups.select { |c| c.credit_status == true}.count 
end 

를 전달하는 잘못된 방법입니다 볼 수 있듯이?

감사합니다.

답변

1

이상적으로 컨트롤러에 액세스 할 수있는 데이터는 모델 메서드에 매개 변수로 전달되어야합니다. 따라서 코드를 다시 작성하는 것이 가능한지 확인하는 것이 좋습니다. 그러나 여기에 문제에 대한 두 가지 가능한 솔루션이 있습니다. 나는 일반적인 방식대로 나중에 접근하는 것을 선호한다.

접근 1 : 선언 컨트롤러 코드에서 가상 속성

class CardSignup 
attr_accessor call_context 
def call_context 
    @call_context || {} 
end 
end 

: 당신의 CardSignup 모델에서

def create 
    cs = CardSignup.new(...) 
    cs.call_context = params 
    if cs.save 
    # success 
    else 
    # error 
    end 
end 

:

def credit_status_on_create 
    Organization.find(self.organization_id).update_credits(call_context) 
end 

업데이트 조직 모델. 카운트 로직이 변경되었음을 확인하십시오.

def update_credits 
    @organization = Organization.find(call_context[:id]) 
    credit_count = @organization.card_signups.count(:conditions => 
        {:credit_status => true}) 
end 

접근법 2 : 선언 스레드 지역 변수 모든 모델

액세스 컨트롤러 코드 :

def create 
    Thread.local[:call_context] = params 
    cs = CardSignup.new(...) 
    if cs.save 
    # success 
    else 
    # error 
    end 
end 

업데이트 Organization 모델. 카운트 로직이 변경되었음을 확인하십시오.

def update_credits 
    @organization = Organization.find((Thread.local[:call_context] ||{})[:id]) 
    credit_count = @organization.card_signups.count(:conditions => 
        {:credit_status => true}) 
end 
0

attr_accessor를 사용하십시오.

예를 들면,

class << self 
    @myvar = "something for all instances of model" 
    attr_accessor :myvar 
end 
@myothervar = "something for initialized instances" 
attr_accessor :myothervar 

는 다음 각각 ModelName.myvarModelName.new.myvar로 액세스 할 수 있습니다.

+0

이것은 스레드로부터 안전한 솔루션이 아닙니다. –

+0

JRuby를 사용하지 않는 한, 실제로는 다중 스레드되지 않습니다. –

0

레일 2 또는 3을 사용하고 있는지 여부는 알 수 없지만이 목적으로 레일 2를 가정 해 봅니다 (레일 3은 쿼리 작성에 새로운 DSL을 제공합니다).

당신은 다음과 같이 조직 모델에 대한 명명 된 범위를 만드는 고려할 수 :

def credit_status_on_create 
    Organization.update_credits(self.organization_id) 
end 

을 틀림없이 내가 아주의 역할을 이해하지 않습니다 다음과 같이

named_scope :update_credits, 
      lambda { |id| { :include => :card_signup, :conditions => [ "id = ? AND card_signups.credit_status = TRUE", id ] } } 

을 그리고 그것을 사용 귀하의 논리에있는 카운터지만, 나는 당신이 그것을 채택한다면이 제안으로 되돌릴 수 있다고 확신합니다.

관련 문제