Reputation: 41999
I have a query to search a certain category of users (lawyers) by their name in my Rails app (which uses a Postgres db) like this
@users = User.where(:lawyer => 'true').text_search(params[:query])
This is the method on the User.rb class
def self.text_search(query)
if query.present?
where("name @@ :q", q: query)
else
scoped
end
end
Instead of using where.(:lawyer => 'true')
in the controller, I wanted to (even though it doesn't affect the query) put that condition inside the method on User.rb class like this
@users = User.text_search(params[:query])
def self.text_search(query)
if query.present?
where("name @@ :q", q: query, :lawyer => 'true')
else
scoped
end
end
However, now the search doesn't work (or rather it just searches by the name query)
How would I add that lawyer == true condition at the in the text_search method.
Upvotes: 0
Views: 128
Reputation: 5528
I'd use a scope:
class User < ActiveRecord::Base
scope :lawyers, :conditions => { :is_lawyer => true }
end
Then in the controller:
@users = User.lawyers.text_search(params[:query])
You could go all out and define a class method on the user model:
def self.lawyers_named(name)
lawyers.text_search(name)
end
Then call it with:
@users = User.lawyers_named(params[:query])
Upvotes: 2