2013-06-03 32 views
-1

我使用this gist在我的Rails應用程序中構建自動完成功能。通過Rails 4中的字符串數組自動完成

我在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格式?

+0

的[*要旨的第一行*](https://gist.github.com/map7/1347080#file-rails-org-L1)顯示「自動完成在Rails 3.1下「,並且你在Rails 4中使用它? – Substantial

+0

它正在使用Rails 4.但現在我的需求改變了,我想以更復雜一點的方式自動完成。我將首先在鞋子(模型屬性)中保存多個逗號分隔的單詞。然後在鞋表的所有行中存在所有單詞的基礎。然後將其全部分割在逗號的基礎上,使其成爲單個單詞並將所有這些單詞用於自動完成。 – Kashiftufail

+0

所以你基本上想要一個CSV字符串充當多個自動完成值? – Substantial

回答

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