Tallboy
Tallboy

Reputation: 13407

Add quotes to an ID in json with rails

my current json output is "id":3,"name":"test", and I need the 3 to be "3".

How would I go about doing this in rails?

  def search
    @tags = Tag.where("name like ?", "%#{params[:q]}%")
    respond_to do |format|
      format.json { render :json => @tags.to_json(:only => [:id, :name]) }
    end
  end

Upvotes: 1

Views: 298

Answers (3)

Tallboy
Tallboy

Reputation: 13407

This was the only solution that worked for me:

  def search
    @tags = Tag.where("name like ?", "%#{params[:q]}%")
    respond_to do |format|
      format.json { render :json => @tags.map {|t| {:id => t.id.to_s, :name => t.name }} }
    end
  end

Upvotes: 0

Chuck Callebs
Chuck Callebs

Reputation: 16431

Sergio's solution will work. However, if you're doing this in more than one place, I would suggest overriding Rails' built in function as_json.

In your Tag model:

def as_json(options={})
  options[:id] = @id.to_s
  super(options)
end

Your controller method will remain unchanged. This is untested, but should work.

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

Something like this:

format.json do
  tags = @tags.to_json(:only => [:id, :name])
  render :json => tags.map{|t| t['id'] = t['id'].to_s; t}
end

Upvotes: 1

Related Questions