【问题标题】:PG::Error: ERROR: operator does not exist: integer ~~ unknownPG::Error: 错误: 运算符不存在: 整数 ~~ 未知
【发布时间】:2013-07-01 09:56:08
【问题描述】:

我正在使用 Postgres 作为数据库的 Rails 项目中创建搜索功能。

这是我的代码

def self.search(search)
   if search 
    find(:all, :conditions => ["LOWER(name) LIKE LOWER(?) OR LOWER(city) LIKE LOWER(?) OR LOWER(address) LIKE LOWER(?) OR (venue_type) LIKE (?)", "%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%"])
    else
      find(:all)
    end
  end

但我的问题是“venue_type”是一个整数。我为venue_type做了一个case switch

def venue_type_check
    case self.venue_type
      when 1
        "Pub"
      when 2
        "Nattklubb"
    end
end

现在我的问题是:当venue_type 是int 时,我如何在查询中找到某些内容?

【问题讨论】:

  • 请尝试:find(:all, :conditions => ["LOWER(name) LIKE LOWER(?) OR LOWER(city) LIKE LOWER(?) OR LOWER(address) LIKE LOWER( ?) OR (venue_type = ?)", "%#{search}%", "%#{search}%", "%#{search}%", search.to_i])
  • 错误PG::Error: ERROR: operator does not exist: integer ~~ unknown在哪里被抛出?
  • @BachanSmruty 我尝试了你的方式,但是当我搜索“Nattklubb”(venue_type)时,我没有得到任何结果。 ://
  • @rsvmrk,请检查我的答案。希望它对你有用。

标签: ruby-on-rails postgresql search integer


【解决方案1】:

请尝试此代码。这里我在 where 子句中添加了 switch case。

def self.search(search)
           if search 
            find(:all, :conditions => ["LOWER(name) LIKE LOWER(?) OR LOWER(city) LIKE LOWER(?) OR LOWER(address) LIKE LOWER(?) OR (venue_type = CASE WHEN 'pub' = ? THEN 1 WHEN 'nattklubb' = ? THEN 2 END)", "%#{search}%", "%#{search}%", "%#{search}%", "#{search.downcase}", "#{search.downcase}"])
            else
              find(:all)
            end
end

【讨论】:

  • 是的,我尝试了您的代码,但由于某种原因,我收到此错误:PG::Error: ERROR: syntax error at or near ")" LINE 1: ...ub' = '% white%' THEN 1 WHEN 'Nattklubb' = '%white%' THEN 2)) ^ : SELECT "venues".* FROM "venues" WHERE (LOWER(name) LIKE LOWER('%white%') OR LOWER(city ) LIKE LOWER('%white%') OR LOWER(address) LIKE LOWER('%white%') OR (venue_type = CASE WHEN 'Pub' = '%white%' THEN 1 WHEN 'Nattklubb' = '%white% ' 那么 2))
  • @rsvmrk,对不起,我错过了开关盒中的 END。我已经修改了它。请立即查看
  • 我不知道我的评论现在是否有意义,很抱歉。
  • 不不。。谢谢你的评论,否则我怎么知道,我的回答有一些错误。。谢谢你的评论.. :)
  • 哦,谢谢,结果有点……有趣的是:当我搜索 1 或 2 时,会出现“Nattklubb”或“Pub”。我怎样才能扭转这种局面?
【解决方案2】:

我认为你必须使用if-else condition in your where clause 类似以下的东西

find(:all, :conditions => ["LOWER(name) LIKE LOWER(?) OR LOWER(city) LIKE LOWER(?)
            OR LOWER(address) LIKE LOWER(?) OR    
    IF(venue_type == 1, 'Pub', IF(venue_type == 2, 'Nattklubb2',  '')) LIKE (?)", 
                 "%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%"])

【讨论】:

    【解决方案3】:

    如果您使用的是 rails 3.2 或更高版本,则应使用 where( [] ) 代替 find

    where( [ "field like ?", field ] ).order(). ...
    

    另外,在使用 pgsql 时,为什么不使用 ilike 而不是 likelower

    在您搜索 int 或非 int 时,我会使用不同的查询。

    search.to_i != 0

    【讨论】:

      猜你喜欢
      • 2015-07-13
      • 2013-06-05
      • 2019-07-03
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多