I know this question already has an answer, but there is also a nice gem you could use called active_model_serializers. This lets you specify exactly which properties you want in your JSON output for different models and even let's you include relationships to other models in your response.
Gemfile:
gem 'active_model_serializers', '~> 0.10.0'
Then run bundle install.
You can then create a serializer using the generator command:
rails g serializer user
which will create the serializer in project-root/app/serializers/.
In your serializer, you can whitelist the attributes you would like:
project-root/app/serializers/user_serializer.rb:
class UserSerializer < ActiveModel::Serializer
attributes :id, :email
end
Now any time you return a User object it will only output those two attributes, id and email.
Want to print out related models? Easy. You can just add the relationship in your serializer and it will include those related models in your JSON output.
Pretend a user "has many" posts:
class UserSerializer < ActiveModel::Serializer
attributes :id, :email
has_many :posts
end
Now your JSON outputs should look something like:
{
"id": 1,
"email": "[email protected]",
"posts": [{
id: 1,
title: "My First Post",
body: "This is the post body.",
created_at: "2017-05-18T20:03:14.955Z",
updated_at: "2017-05-18T20:03:14.955Z"
}, {
id: 2,
title: "My Second Post",
body: "This is the post body again.",
created_at: "2017-05-19T20:03:14.955Z",
updated_at: "2017-05-19T20:03:14.955Z"
},
...
]
}
Pretty neat and convenient. And if you want to limit the the posts to only print certain columns as well, all you need to do is create a serializer for posts, specify the attributes, and the output will just work.
render json: {user: user.pluck(:id, :email), status: status}will not return the whole serialized user object. If you have simplified the problem in an attempt to provide a minimal scenario, can you please ensure it's still a verifiable description?undefined methodpluck' for #<User`user.attributes.extract!('id', 'name'). Usingas_jsonis better though. My point, basically, was that your question did not describe your error.