【问题标题】:LIKE query compatible with SQLite and PostgreSQL与 SQLite 和 PostgreSQL 兼容的 LIKE 查询
【发布时间】:2016-07-27 03:15:19
【问题描述】:

我正在尝试使LIKE 查询在我的开发中的 SQLite 和生产中的 PostgreSQL (Heroku) 中工作,而不对任一环境使用 if-else 语句。 if-else 语句似乎不是一个可行的选择。

我现在的回答是基于此处提供的解决方案:Generic Ruby solution for SQLite3 "LIKE" or PostgreSQL "ILIKE"?

这是我的课程模型的样子:

class Course < ApplicationRecord
  has_many :enrollments
  has_many :users, through: :enrollments

  has_many :course_subjects
  has_many :subjects, through: :course_subjects

  def self.search(search)
    where("lower(name) LIKE lower(?)", "%#{search}%") 
  end
end

如何构建我的 LIKE 查询以与 SQLite 和 PostgreSQL 兼容?

【问题讨论】:

    标签: ruby-on-rails postgresql heroku sqlite pattern-matching


    【解决方案1】:

    如果我可以提出一些建议,建议在所有环境中使用相同的数据库,以便您以后可以在代码中包含 Postgresql-SQL 部分(出于优化目的等)。

    【讨论】:

    • 我也赞成这个。在不同的环境中使用不同的数据库并不是一个好习惯。
    【解决方案2】:

    使用 Arel 可以轻松解决此问题:

    def self.search(search)
        Course.where(Course.arel_table[:name].matches("%#{search}%"))
    end
    

    【讨论】:

      猜你喜欢
      • 2021-02-20
      • 2015-08-11
      • 2014-10-02
      • 2016-10-30
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 2020-12-06
      相关资源
      最近更新 更多