Ruby on Rails - 在 where 查询中使用 Float::INFINITY,有什么缺点吗?
Ruby on Rails - Using Float::INFINITY with where query, any drawbacks?
所以,我的模型中有一个搜索方法如下:
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
现在,如果 max_hourly_rate 为空,那么我会收到此错误:
PG::InvalidTextRepresentation: ERROR: invalid input syntax for type double precision: ""
LINE 1: ...IKE '%%' AND experience >= '5' AND hourly_rate <= '') AND (l...
我没有使用另一个无聊的 if 语句,而是将 max_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
这种方法有什么缺点吗?如果是,有没有更好的解决方案?
一个明显的缺点是您添加的每个条件都会使您的数据库查询更加复杂和缓慢。另一个缺点是这种方法不适用于所有数据库。它可能适用于 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
所以,我的模型中有一个搜索方法如下:
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
现在,如果 max_hourly_rate 为空,那么我会收到此错误:
PG::InvalidTextRepresentation: ERROR: invalid input syntax for type double precision: ""
LINE 1: ...IKE '%%' AND experience >= '5' AND hourly_rate <= '') AND (l...
我没有使用另一个无聊的 if 语句,而是将 max_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
这种方法有什么缺点吗?如果是,有没有更好的解决方案?
一个明显的缺点是您添加的每个条件都会使您的数据库查询更加复杂和缓慢。另一个缺点是这种方法不适用于所有数据库。它可能适用于 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