【问题标题】:How to select all records that start with certain string?如何选择以某个字符串开头的所有记录?
【发布时间】:2016-05-20 19:04:26
【问题描述】:

我有几条以title 开头的记录:

  • 尼克1
  • 尼克2
  • 尼克3
  • 其他名字1

如何选择标题以“Nick”开头的所有记录并以正确的顺序呈现?比如:

@records = Record.where(title starts with: params[:title_name])
render json: @records

【问题讨论】:

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


    【解决方案1】:

    您可以在此处使用LIKE 运算符:

    @records = Record.where('title LIKE ?', "#{params[:title_name]}%").order(:title)
    

    我更愿意将这些放在一个范围内:

    scope :title_search, ->(title){ where('title LIKE ?', "#{title}%") }
    

    并通过以下方式调用它:

    @records = Record.title_search(params[:title_name])
    

    【讨论】:

    • 对于“started with certain string”,百分号的正确位置是相反的:'title LIKE ?', "#{title}%"
    • @mudasobwa 非常感谢。你说得对。我更新了答案并纠正了我的错误
    • 谢谢,它有效,但我遇到了资本敏感性问题。参数中的标题没有大写,而数据库中的标题有大写。结果,它不返回任何记录。有没有办法解决这个问题并使“查询”大写不敏感?
    • 尝试Record.where('LOWER(title) LIKE ?', "#{params[:title_name].downcase}%").order(:title) 不区分大小写。 SQL 函数也可以是LCASE。取决于您的数据库。
    【解决方案2】:

    你可以试试Searchlogic

    那么就这么简单:

    @search = Record.new_search(params[:search])
    @search.condition.title_starts_with = "Nick"
    @models = @search.all
    

    或者你可以试试

    Record.where("title LIKE :prefix", prefix: "#{prefix}%")
    

    【讨论】:

      【解决方案3】:

      我建议使用 arel,如“How to do a LIKE query in Arel and Rails?

      records = Record.arel_table
      Record.where records[:title].matches("#{params[:title_name]}%")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-05
        • 2011-06-27
        • 1970-01-01
        • 2022-12-24
        • 2010-09-08
        • 1970-01-01
        相关资源
        最近更新 更多