0

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 = )

1 Answer 1

2

Your autocomplete action must render something like

render json: @tags.map{ |tag| {:label => "#{tag.name} x #{tag.count}", :value => tag.name} }
Sign up to request clarification or add additional context in comments.

1 Comment

wow i did not know you could do that. many thanks! i will keep that in mind

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.