-1

I'm using this gist to build autocomplete functionality in my Rails app.

I'm saving record in Shoe model attribute like below

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

My controller code is below

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

How do I render it in json format?

6
  • The very first line of the gist says "autocomplete under Rails 3.1," and you're using it with Rails 4? Commented Jun 3, 2013 at 8:09
  • It is working with Rails 4. But now my requirement changed that i want to autocomplete in little more complex way. I will first save multiple comma separated words in Shoe (model attribute).Then on base of all words exists in all rows of shoes table. Then split it all on the base of comma to make it single word and use all these words for autocomplete. Commented Jun 3, 2013 at 8:13
  • So you basically want a single CSV string to act as multiple autocomplete values? Commented Jun 3, 2013 at 8:21
  • Not multiautocomplete, use it for single autocomplete(for one word) Commented Jun 3, 2013 at 8:22
  • No, I meant multiple strings that will hit the same Shoe record. For example, if I start typing nike, it will show autocomplete suggestions nike air, nike steam, nike softy, nike strength... all separate words but all pointing to the same Shoe record? Commented Jun 3, 2013 at 8:40

1 Answer 1

1

At last this code works for me.

         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

Also see How get value from array of strings in Ruby 2.0

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.