【问题标题】:How to search an integer field in ActiveRecord?如何在 ActiveRecord 中搜索整数字段?
【发布时间】:2013-05-14 17:47:32
【问题描述】:

我希望用户能够使用此功能搜索我的数据库:

def self.search(query)
  new_query = (query.to_d * 100).to_i
  where("price_in_cents LIKE ?", new_query)
end

问题是我所有的prices 都作为integers 存储在数据库中,所以如果有人搜索“10.99”,他应该实际上搜索“1099”。

但是上面的函数不起作用,我想知道我做错了什么。

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 activerecord ruby-on-rails-3.2


    【解决方案1】:

    你为什么用“like”来比较数字?您应该使用“=”或“>=”等。

    def self.search(query)
      new_query = (query.to_d * 100).to_i
      where("price_in_cents = ?", new_query)
    end
    

    【讨论】:

    • 是的,好点。实际上你是对的。问题是我的搜索现在有点太苛刻了。例如。如果我搜索“5”,将找不到“55”的价格。
    • 然后你应该创建一个更复杂的 where 语句,它将你的列转换为字符串,以便执行“like”比较。
    【解决方案2】:

    好的,我最终使用了这个:

    def self.search(query)
      string = query.to_s.gsub('.','')
      where("amount_in_cents LIKE ?", "%#{string}%")
    end
    

    感谢 @grotori 让我走上正轨!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-15
      • 2018-12-02
      • 2015-01-24
      相关资源
      最近更新 更多