Dynamic Scope Methods in Edge Rails
Posted in Rails, Ruby on Rails, ror on December 30th, 2008 by admin – 3 CommentsWe perform simple queries using dynamic finder and for commonly used query logic we use named scope.
named_scope :active, :conditions => { :status => true}
User.active
# SELECT * FROM users WHERE status=1
but we cant chain query conditions when using these dynamic finders.
With the addition of dynamic scopes, we can now have a way to both quickly specify query logic and chain further conditions.
User.scoped_by_user_name(user_name).scoped_by_password(password)
#=> SELECT * FROM users WHERE user_name = user_name AND password = password
User.scoped_by_user_name(user_name).scoped_by_password(password).scoped_by_status(true)
#=> SELECT * FROM users WHERE user_name = user_name AND password = password AND status=1
We can now use class methods like scoped_by_user_name(user_name) and scoped_by_user_name_and_password(user_name, password) that will use the scoped method with attributes you supply.