How to pass attr accessors in your JSON response
Published in March 2020
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]
Now distance is present in your json! 🎉
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.