通过Rails 4中的字符串数组自动完成

时间:2013-06-03 07:54:15

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

我正在使用this gist在我的Rails应用中构建自动完成功能。

我正在Shoe模型属性中保存记录,如下所示

"nike air, nike steam,nike softy ,nike strength"  #comma separated words

我的控制器代码在

之下
def shoes
  shoes_list = []
  shoes = Shoe.all

  shoes.each do |shoe|
    shoes_list << shoe.model.split(',')
  end unless shoes.blank?

  if params[:term]
    like = "%".concat(params[:term].concat("%"))
    # shoes = Shoe.where("model like ?", like)
    # **How i make like query to "shoes_list" same like above commented line?**
  else
    shoes = Shoe.all
  end

  list = shoes.map { |u| Hash[id: u.id, label: u.model, model: u.model] }
  render json: list
end

如何以json格式呈现它?

1 个答案:

答案 0 :(得分:0)

最后这段代码对我有用。

         def shoes
              shoes_list = []
              shoes = Shoe.all
              shoes.each do |shoe|
                shoes_list << shoe.model.split(',')
              end unless shoes.blank?
              shoes_list.flatten!

              if params[:term]
                shoes = shoes_list.grep(Regexp.new( Regexp.escape(params[:term]), "i" ))
              else
                shoes = shoes_list
              end
            list = shoes.map {|u| Hash[id: u, label: u, name: u]}
            render json: list
          end

另见How get value from array of strings in Ruby 2.0