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?
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.
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.
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.
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.
Something like this should work:
render :json => @programs, :include => {:insurer => {:only => :name}}, :except => [:created_at, :updated_at]
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] )
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With