to_json vs as_json in Rails API


Bookmark and Share

Recently we have been working on Rails API. During that time, we were curious about the difference between as_json and to_json. In this article, we are sharing the difference we learned.

to_json in Rails API

Let’s discuss how we started out building our APIs using ‘to_json’. to_json will return JSON string representing the hash. Option are passed to each element.

In to_json without any option,  the returned JSON string will include all the model attributes

to_json had some great options of ActiveRecord objects. We could just tell the method to only render certain attributes, or to include association or method calls. We had:

  • only – Only show column names in the output as specified in the list
  • except – Show all column names except the ones specified in the list

to_json works fine and seamlessly ok, as long as the database schema is deeply coupled with the API output.When it takes the next level where we want to render a certain attribute in json it start to break.

This will start to generate a bit load to controllers. Such methods of generating json don’t feel quite right and begin to break down. This is because the to_json is interested in ‘serializing’ a …

Read More

Fixtures in Rails Tests


Bookmark and Share

Fixtures  are one of the important thing in Rails testing. Testing the application helps to debug it more efficiently and ensures the desired functionality to the application. Let’s have a look on them.

It is used to manage the test data. It tests against the real data and is written in YAML files. For each model in the application, there is a .yml file in the test/fixtures directory. When we generate the model using rails g it will automatically create the .yml file also. Here you can see an example,

Here ‘Matz’ is the fixture name. And the name and message are the fields in the User model.

Fixtures come in 3 flavours:

  • YAML fixtures: It is a file format which describes data structures in human-readable format.These are stored in a single file per model(above example is in yaml format).
  • CSV fixtures: Here values are kept in the Comma Separated Value (CSV) format. These are stored in a single file but instead end with the .csv file extension.

Eg:

  • Single-file fixtures: These are the original format for Active Record.

Eg:

Creating multiple/random items in fixtures

You can create multiple items as:

When you add fixtures, they get IDs based on …

Read More