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.

ruby
1
render json: user, methods: [:distance]

Level up your web development skills

Get articles, guides and interviews right in your inbox. Join a community of fellow developers.

No spam. Unsubscribe at any time.