문제

Just like dynamic finder methods in rails, is there any way to have dynamic finder methods for associated models?

Consider the following models

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

class Note
   belongs_to :user
   attr_acccessible :note
end

How can I call a dynamic finder of note attribute from the User object?

도움이 되었습니까?

해결책

Scopes are class methods, so User.scope_name (more on scopes here: http://guides.rubyonrails.org/active_record_querying.html#scopes). If you want to find a specific note that belongs to that user object, you could define an instance method - something like this:

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

or

def last_note
   self.notes.last
end

And use it the following way:

@user.note_with_content("This is a note")

@user.last_note
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top