2012-08-10 4 views
0

레일의 동적 파인더 메소드와 마찬가지로 연결된 모델에 동적 파인더 메소드를 사용할 수 있습니까?rails 애플리케이션에 named_scopes를 동적으로 추가하십시오.

는 다음과 같은 모델

class User 
    attr_accessible :name, :phone_no 
    has_many :notes 
end 

class Note 
    belongs_to :user 
    attr_acccessible :note 
end 

가 어떻게 사용자 개체에서 참고 속성의 동적 파인더를 호출 할 수 있습니다 고려?

+0

Rails/Ruby의 모든 기능은 무엇입니까? – Andrei

+0

Ruby 버전 : 1.8.7 Rails 버전 : 3.0.4 베타 –

답변

1

범위는 클래스 메서드이므로 User.scope_name (자세한 내용은 여기에서 범위 : http://guides.rubyonrails.org/active_record_querying.html#scopes)입니다.

def note_with_content(content_string) 
    self.notes.where(:content => "#{content_string}") 
end 

또는

def last_note 
    self.notes.last 
end 

을하고 다음 방법을 사용하십시오 :

이런 식 - 해당 사용자 개체에 속하는 특정 노트를 찾으려면, 당신은 인스턴스 메서드를 정의 할 수 있습니다
@user.note_with_content("This is a note") 

@user.last_note 
+0

흠, 대답은 좋지만이 인스턴스 메소드를 동적으로 추가해야한다면 어떻게해야합니까? 새로운 속성이 Note 클래스에 동적으로 추가되었다고 가정하고 그 속성에 대한 인스턴스 메소드도 제공하려고합니다. 동적으로 어떻게 할 수 있습니까? –

+0

'def note_with_attribute (attribute_name, value)'//'self.notes.where ("# {attribute_name}"=> "# {value}")'//'end' – Andrei

+0

^^^ 검색 할 속성의 이름을 – Andrei

관련 문제