Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include associated model when rendering JSON in Rails

Right now I have this line:

 render json: @programs, :except => [:created_at, :updated_at]

However, since a Program belongs_to a Company I would like to show the Company name instead of the Company Id.

How can I include the company name when rendering Programs?

like image 591
Hommer Smith Avatar asked Jul 18 '13 17:07

Hommer Smith


People also ask

How to view appointments in rails using render JSON?

By using render json:, we are converting all the model instances into JSON. to_json method can add tacked on, but it is optional, as it will be called implicitly, thanks to Rails doing work behind the scenes. Once you have the routes, controller, and models set up, you can start the Rails server to view your appointments.

Can I use JSON in a Rails application?

If your Rails application presents an API that utilizes JSON, it can be used with popular Javascript frameworks as well as any other application that can handle JSON. The JSON serialization process consists of two stages: data preparation and transformation to the JSON format. Data preparation consists of transforming Ruby objects into a hash map.

What is fast JSON API in rails?

Fast JSON API is a gem you can install in your project. It is one of many gems that you can use. Fast JSON API gives us a new rails generator, serializer, which allows you to quickly create a serializer class. You will need a serializer class for each model, for which you have data you want to serialize.

How to serialize a person model in rails?

If you have a Person model and each person has email and name attributes, then data ready for serialization would look like the following: Notice that in Rails you can call the #to_json method on a model instance. It will return a hash map with all model attributes.


3 Answers

Something like this should work:

render :json => @programs, :include => {:insurer => {:only => :name}}, :except => [:created_at, :updated_at]
like image 196
Nobita Avatar answered Oct 25 '22 22:10

Nobita


i was getting the same "can't clone Symbol file" error while rendering json with includes from a controller method. avoided it like so:

render :json => @list.to_json( :include => [:tasks] )
like image 20
Sean M Avatar answered Oct 25 '22 23:10

Sean M


You can also do this at the model level.

program.rb

  def as_json(options={})
    super(:except => [:created_at, :updated_at]
          :include => {
            :company => {:only => [:name]}
          }
    )
  end
end

Now in your controller:

render json: @programs
like image 13
Abram Avatar answered Oct 25 '22 22:10

Abram