2011-08-17 2 views
1

메시지라는 모델이 있습니다. time_received_or_sent라는 필드가 데이터베이스에 저장되어 있습니다. 들어오는 메시지에는 time_recieved 메시지가 있고 보내는 메시지에는 보낸 시간이 있습니다. 두 가지 메시지가있을 수 없습니다. 모델에서 이들을 결합하여 편집 할 때 time_received와 time_sent가 해당 필드를 가리킬 수 있습니까? 내 모델에는 꽤 쓸모없는 4 가지 방법이 있습니다.레일에서 동일한 필드로 폴드하는 모델의 속성을 어떻게 단순화 할 수 있습니까?

Model Message < ActiveRecord::Base 
    ... 
    def time_received=(time_received) 
     time_received_or_sent = time_received 
    end 

    def time_received 
     return time_received_or_sent 
    end 

    def time_sent=(time_sent) 
     time_received_or_sent = time_sent 
    end 

    def time_sent 
     return time_received_or_sent 
    end 
    end 

나는 훨씬 더 짧은 것을 선호합니다.

내가 아닌 다른 뭔가를 찾고 있어요 :

def time_sent; time_received_or_sent; end 
def time_received; time_received_or_sent; end 
def time_sent=(time_sent); time_received_or_sent=(time_sent); end 
def time_received=(time_received); time_received_or_sent=(time_received); end 

, 비록이 가능한 최고 있다면, 나는 그것으로 괜찮아.

+0

내가 알기로 alias_attribute가 밝혀졌습니다. 미안해. 네가 여기 온다면 대답 할거야. –

+0

언제든지 답변을 추가하여 닫을 수 있습니다. – tadman

+0

좋은 생각입니다. 내 평판은 내가 그렇게했을 때 게시 한 직후에 그렇게 논평 할만큼 높지가 않았다. 나는 대답으로 지금 게시 할 것이다. –

답변

0

당신은 항상 다음을 축소 alias_method를 사용할 수 있습니다

class Message < ActiveRecord::Base 
    def time_received=(time_received) 
    time_received_or_sent = time_received 
    end 
    alias_method :time_sent=, :time_received= 

    def time_received 
    time_received_or_sent 
    end 
    alias_method :time_sent, :time_received 
end 

이 같은 방법의 중복 구현을 피하기위한 편리합니다.

1
Model Message < ActiveRecord::Base 
... 
    alias_attribute :time_sent, :time_received_or_sent 
    alias_attribute :time_received: time_received_or_sent 
end 
관련 문제