[RUBY] [Rails] How to search for records where each surname and given name are stored as DB columns

How to search for records where each surname and given name are stored as DB columns

There are many articles already published, but I made a note so that I don't forget the ones I use often.

name = 'Yamada Taro'
scope = User.all

if name.include?(' ') || name.include?(' ')
    #Replace full-width space with half-width space
    name = name.tr(' ', ' ') if name.include?(' ')
    #Split surname / first name
    last_name, first_name = name.split(' ')
    #Search by condition
    scope = scope.where('last_name LIKE ? AND first_name LIKE ?', "%#{last_name}%", "%#{first_name}%")
else
    #If only one of the first and last names is entered
    scope = scope.where('last_name LIKE :name OR first_name LIKE :name', name: "%#{name}%")
end

reference

Recommended Posts

[Rails] How to search for records where each surname and given name are stored as DB columns
How to implement search function with rails (multiple columns are also supported)
[Rails] How to change the page title of the browser for each page
[Docker] How to create a virtual environment for Rails and Nuxt.js apps
(For beginners) [Rails] Time saving tech! How to install and use slim