Rails JSON Virtual Attributes
I was working on a rails application that responded with the following JSON:
Even though I have access to the user_id
attribute of this post, I wanted to be able to show the user name or email without having to make another HTTP request.
To add a new attribute to this JSON, I needed to add a few methods to extend ActiveRecord::Base
’s as_json
method.
The super.as_json(
… adds whatever attributes you specify for each one of the records from your model.
Since these methods are in the Post
class, we can access the current post with self
.
If there is no user for a given post, self.user.email
would throw an undefined method for nil:NilClass
,
so I prepend that with self.user &&
to make sure the user exists first.