0

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")
rubyprince
  • 17,559
  • 11
  • 64
  • 104

3 Answers3

1

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.

Community
  • 1
  • 1
LapinLove404
  • 1,939
  • 1
  • 21
  • 26
1

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]}}
Rishav Rastogi
  • 15,484
  • 3
  • 42
  • 47
  • why are you using LIKE here...why cant you use like this `named_scope :find_by_name, lambda {|name| {:conditions => ["first_name = ? or last_name = ?", name.split(' ').first, name.split(' ').last]}} ` – rubyprince Feb 14 '11 at 11:19
  • I get it..if the last name contains middle name also, we will miss the record if we directly compare... – rubyprince Feb 14 '11 at 11:32
0

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');

Syed Aslam
  • 8,707
  • 5
  • 40
  • 54