Rails virtual attribute search or sql combined column search Rails virtual attribute search or sql combined column search sql sql

Rails virtual attribute search or sql combined column search


You can used a named_scope in your user.rb:

named_scope :find_by_full_name, lambda {|full_name|   {:conditions => {:first => full_name.split(' ').first,      :last => full_name.split(' ').last}}}

Then you can do User.find_by_full_name('John Carver')

new stuff in response to changes in requirement

named_scope :find_by_full_name, lambda {|full_name|   {:conditions => ["first LIKE '%?%' or last LIKE '%?%'",     full_name.split(' ').first, full_name.split(' ').last]}}


I found Jim's answer helpful as well. Thanks. I'd make a slight change though.This current code causes you to loose any middle names. What I have below is a bit messy but preserves middle names and compound last names (think Jean-Claude van Damme). Everything after the first name goes in the last_name field.

named_scope :find_by_full_name, lambda { |full_name|  {:conditions => {:first_name => full_name.split(' ').first,    :last_name => full_name.split(' ')[1, full_name.split(' ').length-1].join(' ')}   }}

Of course any cleaner way to do this is welcome.