DEV Community

Cover image for How to get a Rails Api model method in JSON.
Othmane Namani
Othmane Namani

Posted on

How to get a Rails Api model method in JSON.

Hi guys, this other article about web development with Ruby On Rails.

We will learn how to include model methods in JSON, to use it as a JavaScript object attribute. But first, we should know what it is a Model, and what is JSON. We will see also in this article as_json and to_json methods.

"A Rails Model is a Ruby class that can add database records (think of whole rows in an Excel table), find particular data you're looking for, update that data, or remove data. These common operations are referred to by the acronym CRUD - Create, Remove, Update, Destroy" -LaunchAcademy.

This is a Rails model example here:

class Person < ActiveRecord::Base
  has_many :projects
  validates :first_name, presence: true
  validates :last_name, presence: true
end

We have a model called Person, which requires the presence of first_name and last_name attributes to create an instance of Person, also it could have some projects. Let's see what is JSON.

"JSON stands for JavaScript Object Notation
JSON is a lightweight format for storing and transporting data
JSON is often used when data is sent from a server to a web page
JSON is "self-describing" and easy to understand"
-W3scools.

A JSON example to show a users object, users contains an array of 3 users objects:

{
  "users":[
     {"first_name":"John", "last_name":"Doe"},
     {"first_name":"Anna", "last_name":"Smith"},
     "first_name":"Peter", "last_name":"Jones"}
  ]
}

To see how to convert a JSON text to a JavaScript object, just take one minute to read this lesson on W3schools.

So that was a brief introduction to Model and JSON with some examples.

Now, we will add a method to our Person model above. This is as simple as declaring a method in a Ruby class, let us call it full_name.
The model methods often use its model attributes, full_name will take the first_name and last_name attributes and combines them to return the full name of a Person instance.

class Person < ActiveRecord::Base
  has_many :projects
  validates :first_name, presence: true
  validates :last_name, presence: true
  def full_name
    "#{first_name} #{last_name}"
  end
end

In this case, any instance of Person will get a full_name attribute. For example: if we create person-1 with a first name "John", and last name "Doe", person-1.full_name will be "John Doe", but only with Ruby, because that is not the same thing for JSON.

Using to_json method will return a JSON string that includes the person-1 attributes and values. There will be no full_name attribute, person-1.to_json will give us:

{"first_name":"John", "last_name":"Doe"};

Great! Our next step is to include full_name attribute in JSON. To do this task we will use other Rails built-in method called as_json.

What is as_json? => Take a look at this documentation.

Well, as_json method takes options as parameters, if we pass :methods as options and call super we overwrite the method to_json in our model, This will call as_json method version of the super class with :methods options, so that it will serialize our model with full_name attribute.

class Person < ActiveRecord::Base
  has_many :projects
  validates :first_name, presence: true
  validates :last_name, presence: true

  def as_json(options={})
    options[:methods] = [:full_name]
    super
  end

  def full_name
    "#{first_name} #{last_name}"
  end
end

And now, we can see the full_name attribute appeared in our JSON object, and person-1.to_json now returns:

{"first_name":"John", "last_name":"Doe", "full_name":"John Doe"};

Json help Model method

Like this, we could use a Rails API model method, as an attribute in JavaScript, after converting the JSON object to a JavaScript one.

At last, I strongly recommend:
This post on Stack-over-flow: https://stackoverflow.com/questions/10821138/custom-model-method-that-should-be-included-in-json-serialization.

Read about Rails Active Record for further understanding Rails Models: https://guides.rubyonrails.org/active_record_basics.html.

This article for a better understanding of what is to_json and as_json: https://blog.arkency.com/how-to-overwrite-to-json-as-json-in-active-record-models-in-rails/.

Top comments (0)