【发布时间】:2020-07-17 08:38:42
【问题描述】:
我有包含以下字段的商家表
Merchant(id: integer, name: string, logo: string, description: text, categories: string, created_at: datetime, updated_at: datetime)
我想使用 name 属性运行 first_or_create 查询。问题是名称列包含单引号,例如 Brandy's Boy。
mname = "brandy's boy"
conds = "lower(name) = #{mname}"
Merchant.where(conds)
Merchant Load (1.5ms) SELECT "merchants".* FROM "merchants" WHERE "merchants"."deleted_at" IS NULL AND (lower(name) = 'brandy's boy ') LIMIT $1 [["LIMIT", 11]]
输出:
#<Merchant::ActiveRecord_Relation:0x000055d0f72a2ce0>
但是当我运行静态查询时,这会给我输出。
Merchant.where("lower(name) = ?", 'Brandy\'s Boy'.downcase)
Merchant Load (3.7ms) SELECT "merchants".* FROM "merchants" WHERE "merchants"."deleted_at" IS NULL AND (lower(name) = 'brandy''s boy') LIMIT $1 [["LIMIT", 11]]
#<ActiveRecord::Relation [#<Merchant id: 1413, name: "Brandy's Boy", logo: nil, description: "ABC", categories: [], created_at: "2020-07-17 07:32:29", updated_at: "2020-07-17 07:32:29">]>
但是变量 mname 是在循环中填充的,它是动态的。所以在这种情况下,我需要转义单引号并获得所需的结果(现有 Brandy's Boy Merchant 对象)
请帮忙。
【问题讨论】: