0

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?

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Although you can just do something like: @users = User.all.to_json :only => [:id, :name]; render :json => @users in the controller but still I prefer Active Serializer since it organise the presentation layer.
1

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

1 Comment

I get this part, but my model does not have id or name. It has different field names, how do I pass modification so it will get outputted as id and name?
0

Maybe in your controller

require 'json'

# ...

def show_json
  user_obj_to_json = User.first.to_json
  render user_obj_to_json
end

1 Comment

actually, what i am trying to do is change the field names of my current field names in my model. i have now category_id and category_name, i simply want them both changed to id and name.

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.