Search code examples
jqueryruby-on-railsjsonjquery-tokeninput

adding a count feature from a tags drop down using json, jquery and rails


im following the railscasts using jquery tokeninput

http://railscasts.com/episodes/258-token-fields-revised

in creating autocomplete tag tokens and have successfully done so. however, ive been trying to add a count attribute, very similar to stack overflows tags counter.

i have in my tags#index

    @tags = Tag.order(:name)
    #@tags = Tag.order(:name).where("name like ?", "%#{params[:term]}%")
    respond_to do |format|
        format.html
        format.json { render json: @tags.tokens(params[:q]) }
    end

when i render, it calls my tokens method which is...

  def self.tokens(query)
    tags = where("name like ?", "%#{query}%")
    if tags.empty?
        [{id: "<<<#{query}>>>", name: "New: \"#{query}\""}]
    else
        puts tags.inspect
        tags
    end
  end

if i type the word 'steelswarm' and inspect the tags that gets returned, on my console it says...

[#<Tag id: 4, name: "steelswarm", created_at: "2012-05-11 01:49:55", updated_at: "2012-05-11 01:49:55", count: 2>]

when the user starts typing the word 'steelswarm' i want the dropdown to display 'steelswarm x 2' since it has a count of two.

ive tried doing

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

in my else statement but the drop down stops rendering. it cant even find the first letter anymore. what am i doing wrong?

don't the :label and :value attributes belong to jquery as a whole?

ive also been looking at the options from

http://loopj.com/jquery-tokeninput/

but i cant seem to find something that would work or at least i could think of... sorry im not very familiar with json and jquery so help would be much appreciated = )

thank you.


Solution

  • i fixed it. it seems like the token only has an :id and :name attribute. so i did..

    tags.map{ |tag| {  id: "#{tag.id}", name: "#{tag.name} # #{tag.count}" } }