简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM