我刚开始使用Ruby on Rails进行开发,并尝试在用户模式下定义搜索范围。使用以下范围,我可以根据用户的名字或姓氏搜索用户:
scope :_s, -> (s) {
where(
'unaccent(LOWER(email)) like unaccent(LOWER(?))
OR unaccent(LOWER(first_name)) like unaccent(LOWER(?))
OR unaccent(LOWER(last_name)) like unaccent(LOWER(?))',
"%#{s}%", "%#{s}%","%#{s}%") }
我无法启动并运行搜索全名,我认为以下内容可行:
scope :_s, -> (s) {
select('(first_name || " " || last_name) as \'full_name\', *')
where(
'unaccent(LOWER(email)) like unaccent(LOWER(?))
OR unaccent(LOWER(first_name)) like unaccent(LOWER(?))
OR unaccent(LOWER(last_name)) like unaccent(LOWER(?))
OR unaccent(LOWER(full_name)) like unaccent(LOWER(?))',
"%#{s}%", "%#{s}%","%#{s}%","%#{s}%") }
但是这会返回
PG :: UndefinedColumn:ERROR:列“full_name”不存在
据我所知,我的数据库认为我在数据库中查找记录,但是如何告诉它查看上面定义的full_name?
答案 0 :(得分:2)
这就是SQL别名的工作原理,where子句对select子句中定义的别名一无所知。取代
unaccent(LOWER(full_name))
与
unaccent(LOWER(first_name || \' \' || last_name))