-1

我正在使用这个要点在我的 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 格式呈现它?

4

1 回答 1

1

最后这段代码对我有用。

         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

另请参阅如何从 Ruby 2.0 中的字符串数组中获取值

于 2013-06-04T01:50:28.993 回答