Rails virtual attribute search or sql combined column search

自闭症网瘾萝莉.ら 提交于 2019-11-28 09:14:58

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!