0

I have these two tables:

product has_one address

address belongs_to product

When I want to find a product from one city, I do:

Product.all.joins(:address).where(addresses: {city: @city})

When I want to to find all cities with case insensitive is

Address.all.where('lower(city) like ?', @city.downcase)

But now I want a record from another table with case insensitive combined. How can I do ?

I tried some ways and nothing:

Product.all.joins(:address).where(addresses: {"lower(city) like ?", @city.downcase})

gives the error:

SyntaxError: unexpected '}', expecting end-of-input
...ower(city) like ?", "new york"})
...

and the other way:

Product.all.joins(:address).where(addresses: {"lower(city) like ?": @city.downcase})

gives nothing:

#<Product::ActiveRecord_Relation:0x3fb3fc142900>

Obs: I created another question because the old one was wrongly marked as duplicated.

Fillype Farias
  • 532
  • 1
  • 5
  • 16

1 Answers1

1

Product.joins(:address).where "lower(addresses.city) like ?", @city.downcase

Response to comment

No idea what you're talking about "didn't track from the column city on addresses table" - what does "didn't track" mean?

Here's a console session with your models as described showing my code above working just as described:

[14] pry(main)> Address.create city: "New York", product: Product.first
  Product Load (0.3ms)  SELECT  "products".* FROM "products" ORDER BY "products"."id" ASC LIMIT $1  [["LIMIT", 1]]
   (0.1ms)  BEGIN
  Address Create (43.9ms)  INSERT INTO "addresses" ("product_id", "city", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["product_id", 1], ["city", "New York"], ["created_at", "2019-02-27 18:57:37.688063"], ["updated_at", "2019-02-27 18:57:37.688063"]]
   (0.3ms)  COMMIT
=> #<Address:0x00007fb1e4322178 id: 1, product_id: 1, city: "New York", created_at: Wed, 27 Feb 2019 18:57:37 UTC +00:00, updated_at: Wed, 27 Feb 2019 18:57:37 UTC +00:00>
[15] pry(main)> @city = "NEW YORK"
=> "NEW YORK"
[16] pry(main)> Product.joins(:address).where "lower(addresses.city) like ?", @city.downcase
  Product Load (0.7ms)  SELECT "products".* FROM "products" INNER JOIN "addresses" ON "addresses"."product_id" = "products"."id" WHERE (lower(addresses.city) like 'new york')
=> [#<Product:0x00007fb1e52f5e10 id: 1, name: "First Product", created_at: Wed, 27 Feb 2019 18:57:07 UTC +00:00, updated_at: Wed, 27 Feb 2019 18:57:07 UTC +00:00>]
smathy
  • 22,956
  • 5
  • 43
  • 66