1

I have the cars_tables and in its name column I have names with special characters, for example:

car_names = Car.pluck :name
=> ["Cárrozería", "Óther Cars", "Forede Lúis", "Ságara Mbobe"]

The values ​​are automatically parameterized making the special characters disappear

car_name_parameterize << ["Cárrozería", "Óther Cars", "Forede Lúis", "Ságara Mbobe"].map { |name| name.parameterize }.join(', ')
=> ["carrozeria", "other-cars", "forede-luis", "sagara-mbobe"]

and with the parameterized values ​​I would like to do a query but I can't since the names have special characters that prevent me from doing so

first_car_name = car_name_parameterize.first
=> carrozeria
Car.find_by('name ILIKE ?', "%first_car_name%")
=> nil ;; nil because the word **carrozeria** doesn't have í special character, 
Car.find_by_name "carrozería"
=> #<Car:0x300312318 id: 1, name: "carrozería"...> ;; If it does the query without returning nil but it is because I consulted its name manually when placing "carrozería"

In short, I am looking to make the queries with the columns with the same name but with special characters (usually these characters usually have accents) recognized.

I am looking to make queries to the name of the cars table, canceling the special characters, such as the accent between the words for example

I have also tried the gsub method without success.

If you could help me I would be very happy and thank you for taking the time to read me.

Samuel D.
  • 199
  • 10
  • 1
    I think you can use the `unaccent` extension. See more details and different alternatives: https://stackoverflow.com/questions/9243322/postgres-accent-insensitive-like-search-in-rails-3-1-on-heroku – markets Nov 23 '22 at 01:48

2 Answers2

1

You will need to use the unaccent extension (docs: https://www.postgresql.org/docs/current/unaccent.html).

Basically, install the extension:

CREATE EXTENSION unaccent;

And then you will be able to use the unaccent() function:

where("unaccent(name) LIKE ?", "%#{your_value}%")

Read more details and different alternatives in the following entry: Postgres accent insensitive LIKE search in Rails 3.1 on Heroku

markets
  • 6,709
  • 1
  • 38
  • 48
  • While this may (or may not) solve the immediate problem its still a very flawed solution. You're relying on `parameterize` and `unaccent` to do the same conversion and thats gonna bite you in the bum eventually. If you want to reliably be able to use the car names as slugs you should store the slugged version on the table - or just use ids instead. – max Nov 23 '22 at 11:10
0

Thanks to the link that the user @markets shared with me, I used the unaccent method to avoid the settlements and then the lower case and it worked for me.

cart_name = "carrozería"

Car.find_by("lower(unaccent(name)) LIKE ?", "%#{cart_name}%")
Samuel D.
  • 199
  • 10