Reputation: 13407
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
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
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
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