【问题标题】:Ruby on Rails - Using Float::INFINITY with where query, any drawbacks?Ruby on Rails - 将 Float::INFINITY 与 where 查询一起使用,有什么缺点吗?
【发布时间】:2021-06-14 02:27:35
【问题描述】:

所以,我的模型中有一个搜索方法如下:

def self.advanced_search(name, min_experience, max_hourly_rate)
    where('lower(name) LIKE ? AND experience >= ? AND hourly_rate <= ?', "%#{name.downcase}%", min_experience, max_hourly_rate)
end

现在如果 ma​​x_hourly_rate 为空白,那么我会收到此错误:

PG::InvalidTextRepresentation: ERROR:  invalid input syntax for type double precision: ""
LINE 1: ...IKE '%%' AND experience >= '5' AND hourly_rate <= '') AND (l...

我没有使用另一个无聊的 if 语句,而是将 ma​​x_hourly_rate 设置为无穷大(如果它是空白的)

def self.advanced_search(name, min_experience, max_hourly_rate)
    max_hourly_rate = Float::INFINITY if max_hourly_rate.blank?
    where('lower(name) LIKE ? AND experience >= ? AND hourly_rate <= ?', "%#{name.downcase}%", min_experience, max_hourly_rate)
end

这种方法有什么缺点吗?如果有,有没有更好的解决方案?

【问题讨论】:

    标签: ruby postgresql ruby-on-rails-4 search


    【解决方案1】:

    一个明显的缺点是,您添加的每个条件都会使您的数据库查询更加复杂和缓慢。另一个缺点是这种方法不适用于所有数据库。它可能适用于 PostgreSQL,但例如 SQLite 会引发 SQLException。

    我只会添加几个范围并使用它们。作用域是可链接的,作用域可以有一个空的条件。

    scope :by_name, ->(name) { where('lower(name) LIKE ?', "%#{name.downcase}%") if name.present? }
    scope :min_experience, ->(exp) { where('experience >= ?', exp) if exp.present? }
    scope :max_hourly_rate, ->(rate) { where('hourly_rate <= ?', rate.present?) if rate }
    

    使用这样的范围,您可以这样编写查询,而不必关心nil

    self.advanced_search(name, min_exp, max_rate)
      by_name(name).min_experience(min_exp).max_hourly_rate(max_rate)
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 2014-01-22
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      相关资源
      最近更新 更多