我有这两个表:
产品具有一个地址
地址属于产品
当我想从一个城市寻找产品时,我会做:
Product.all.joins(:address).where(addresses: {city: @city})
当我想查找所有不区分大小写的城市
Address.all.where('lower(city) like ?', @city.downcase)
但是现在我要从另一个表中 不区分大小写组合的记录。我该怎么办?
我尝试了一些方法,却一无所获:
Product.all.joins(:address).where(addresses: {"lower(city) like ?", @city.downcase})
给出错误:
SyntaxError: unexpected '}', expecting end-of-input
...ower(city) like ?", "new york"})
...
和另一种方式:
Product.all.joins(:address).where(addresses: {"lower(city) like ?": @city.downcase})
一无所获:
#<Product::ActiveRecord_Relation:0x3fb3fc142900>
obs:我提出了另一个问题,因为旧的错误地标记为重复。
答案 0 :(得分:1)
Product.joins(:address).where "lower(addresses.city) like ?", @city.downcase
不知道您在说什么“没有从地址表上的列城市进行跟踪”-“没有跟踪”是什么意思?
这是一个与您的模型进行的控制台会话,如上所述,显示了我的代码如上所述工作:
[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>]