如何选择以某些字符串开头的所有记录?

时间:2016-02-10 12:15:41

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

我有几条title开头的记录:

  • Nick1
  • Nick2
  • Nick3
  • Othername1

如何选择标题以#34; Nick"开头的所有记录?并按正确的顺序呈现它们?类似的东西:

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

3 个答案:

答案 0 :(得分:2)

您可以在此处使用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])

答案 1 :(得分:0)

您可以尝试Searchlogic

然后它就像:

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

或者你可以尝试

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

答案 2 :(得分:0)

我建议在“How to do a LIKE query in Arel and Rails?

中使用arel
records = Record.arel_table
Record.where records[:title].matches("#{params[:title_name]}%")
相关问题