Sasha
Sasha

Reputation: 3281

rails, parsing a json array for an autocomplete feature

i was wondering if there was a way to parse a json array in this situation. im doing an autocomplete for a tags text field, very similar to stack overflow's tags text field. i wanted to have a count associated with that specific tag.

in one of my views, i have a...

<div class="tags">
    <%= f.label :tag_name, "Tags" %>
    <%= f.text_field :tag_name, data: { autocomplete_source: tags_path} %>
</div>

which in turn calls my articles.js.coffee

jQuery ->
    $('#article_tag_name').autocomplete
        source: $('#article_tag_name').data('autocomplete-source')

and in my tags controller i have...

def index
    @tags = Tag.order(:name).where("name like ?", "%#{params[:term]}%")
    render json: @tags.map{|tag| "#{tag.name} x #{tag.count}"}
end

the code works, and i can retrieve my tags (and their count) from my tags table using ajax.

however i also have this code which is in my model file for the articles

def tag_name=(name)
    self.tag = Tag.find_or_create_by_name(name) if name.present?
end

it lets the user create a tag if it didn't exist. the problem i run into though is this... the tag is now labeled as "Java x 1" and if the user selects that tag, the database now contains "Java x 1" as its own tag as opposed to just "Java".

is there a separate way to parse the json array or for the jquery to handle the name and count separately?

sorry im still quite new to all of this json and jquery. i was following a railscasts. thanks so much for the help = )

Upvotes: 0

Views: 873

Answers (1)

mikdiet
mikdiet

Reputation: 10018

Your autocomplete action must render something like

render json: @tags.map{ |tag| {:label => "#{tag.name} x #{tag.count}", :value => tag.name} }

Upvotes: 2

Related Questions