Search code examples
ruby-on-railsrubynamed-scopedynamic-finders

Add named_scopes dynamically in rails application


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?


Solution

  • 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