Reputation: 69
How do would I format my model so that it will output a json document with an id and name field?
Because my model has custom field names and I am using tokeninput and it requires me to output it to id and name.
any ideas?
Upvotes: 0
Views: 269
Reputation: 1493
You might want to pass a only option to to_json
:only => [:id, :name]
For example, if you want to get id and name of User
User.all.to_json :only => [:id, :name]
If the model does not contain Id and Name as described by OP. Then you use custom select at the time of querying the db.
User.select('filed1 as id, field2 as name').all.to_json
Upvotes: 1
Reputation: 6057
You have so many options here, you can use jbuilder, rabl. But I think the easiest one is to use Active Model Serializers.
Let's say you have a model name User.
First install the bundle, then:
rails g serializer user
Then at app/serializers/user_serializer.rb:
class ArticleSerializer < ActiveModel::Serializer
attributes :id, :name
end
Upvotes: 1
Reputation: 19061
Maybe in your controller
require 'json'
# ...
def show_json
user_obj_to_json = User.first.to_json
render user_obj_to_json
end
Upvotes: 0