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,lambda { |user| where("finish=? and user_id = ?", true, user.id)}
end
And to use we have to pass the current_user object as:
For example to fetch records from projects table with status finish true, we can proceed as follows:
class Project < ActiveRecord::BaseAnd to use it we can call model name dot named_scope method :
named_scope :completed,:conditions=>"finish = true"
end
Project.completedIts 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 !
Great ritesh................... I exactly did the same..................... Good one............Saket Sidana
ReplyDeleteThanks Saki
ReplyDelete