I have User model and I have following in the User model
def name
last_name.blank? ? first_name : "#{first_name} #{last_name}"
end
How can I add a find_by_name function to the User model so that I can do this:
User.find_by_name("Peter Smith")
I have User model and I have following in the User model
def name
last_name.blank? ? first_name : "#{first_name} #{last_name}"
end
How can I add a find_by_name function to the User model so that I can do this:
User.find_by_name("Peter Smith")
I think you can do that using named_scope
Jim and NAD answers for this similar question Rails virtual attribute search or sql combined column search are probably a good start.
You can use this. Split the name into two parts, first_name and last_name and search them
named_scope :find_by_name, lambda {|name| {:conditions => ["first LIKE '%?%' or last LIKE'%?%'", name.split(' ').first, name.split(' ').last]}}
attr_acessible :name
Makes name
like a regular instance variable, which can be accessed plainly as name
or with self.name
. Now, I guess you can do User.find_by_name('somename');