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" 
end
And to use it we can call model name dot named_scope method :
Project.completed
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 user.id as displayed in the below code:

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

And to use we have to pass the current_user object as:
Project.completed(current_user)
Simple, isn't it !

2 comments:

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

    ReplyDelete