How to pass attr accessors in your JSON response

Last updated on December 20, 2021

So you have defined an attr accessor in your model which you want to pass down through a json response. But it doesn’t work.

First of all, the reason why it is not working. Attr_accessor defines a getter and a setter methods. Therefore, if we want to retrieve it from our json, we need to define it as a method. You can read more about attr_accessors in my previous article.

If you have defined an attr_accessor called distance, you can pass the getter method using the following syntax.

render json: user, methods: [:distance]

Invite us to your inbox.

Articles, guides and interviews about web development and career progression.

Max 1-2x times per month.