Thursday, February 10, 2011

To pass current_user object to named_scope in model

named_scope is a way to search records from table repeatedly. Its written in model and one of the easiest way to fetch records.
For example to fetch records from projects table with status finish true, we can proceed as follows:
class Project < ActiveRecord::Base
  named_scope :completed,:conditions=>"finish = true" 
And to use it we can call model name dot named_scope method :
Its very simple, but to pass current_user object to this named_scope is a bit tricky. Suppose we have to find all the projects with status finish, of the current user then it can be done by taking user as an object in it passing as displayed in the below code:

class Project < ActiveRecord::Base 
  named_scope :completed,lambda { |user| where("finish=? and user_id = ?", true,} 

And to use we have to pass the current_user object as:
Simple, isn't it !


  1. Great ritesh................... I exactly did the same..................... Good one............Saket Sidana