Combining multiple objects in an array for json using Grape - ruby-on-rails

I'm using the grape gem in my rails application. When returning a single record I can use the grape active model serializer. When returning multiple objects I run into an undefined error. How should I structure my multiple campaign records?
app/controllers/api/v1/campaigns.rb
Returning Multiple records
resource :campaigns do
desc "Return all campaigns"
get "", root: :campaigns do
#campaign_array = []
#campaigns = Campaign.all
#campaigns.each do |campaign|
#campaign_array << {
backers: campaign.orders.count,
funded: campaign.orders.completed.sum(:quantity),
campaign: campaign
}
end
#campaign_array
end
end
Output - Error
undefined method `read_attribute_for_serialization'
Returning a single record
desc "Return a campaign"
get ":id", root: :campaign do
#campaign = Campaign.where(id: permitted_params[:id]).first!
{
backers: #campaign.orders.count,
funded: #campaign.orders.completed.sum(:quantity),
campaign: #campaign
}
end
Output
{
"backers": 1,
"funded": 2,
"campaign": {
"id": 5,
"min_funding_goal_units": 20,
"product_name": "Another product",
"product_description": "A product description",
}
}

It's look like you return an array which is not serialized.
Does your index works if you just return #campaigns ? (just to be sure that the problem come from the serialization)
Maybe can you try to «help» Grape by indicating format :json below get "", root: :campaigns do
Let me know.

You need to use each_serializer instead of serializer when it's an
array of items
There is an issue in github about this problem. Related issue.

Related

Rails define custom json structure

I'm attempting to structure a json response to mimic an existing structure we have elsewhere in our application (using jbuilder templates). In this specific use case, we are unable to use the jbuilder template because we are preparing the json data for a live update job being fired from a model method, not responding to a server call in the controller.
Desired structure:
{"notes": {
"1": {
"id": "1",
"name": "Jane",
...
},
"2": {
"id": "2",
"name": "Joe",
...
}
}
}
Jbuilder Template (for reference):
json.notes do
for note in notes
json.set! note.id.to_s do
json.id note.id.to_s
json.name note.name
...
end
end
end
I've tried defining a to_builder method in the model class (below), per the jbuilder docs, and active model serializers but can't seem to get the hashes nested under the id attribute. Any direction would be appreciated!
to_builder method
def to_builder
Jbuilder.new do |note|
note.set! self.id do
note.(self, :id, :name, ...)
end
end
end
How about just plain Ruby?
notes.each_with_object({"notes": {}}) do |note, hash|
hash["notes"][note.id.to_s] = note.as_json
end
Or AMS:
adapter = ActiveModelSerializers::Adapter
notes.each_with_object({"notes": {}}) do |note, hash|
hash["notes"][note.id.to_s] = adapter.create(NoteSerializer.new(note))
end

Rails 4 render json with multiple objects and includes

I have a Rails 4 API. When a user search in the view for boats, this method is executed getting all the boats matching the search filters and return an array of boat models as json using render ActiveModel and the :include and :only like this:
render :json => #boats, :include => { :mainPhoto => {:only => [:name, :mime]},
:year => {:only => :name},
# other includes...}
This is working great.
But, additional to this information, in the view, I would like to show the total count of boats like "showing 1 - 20 of 80 boats" because there is a pagination funcionality. So, the point is I need to provide the 80 boats. I would like to avoid send two requests that execute almost the same logic, so the idea is to run the searchBoats method just once and in the result provide the list of boats and the total number of boats in a variable numTotalBoats. I understand numTotalBoats is not a boat model attribute. So, I think it should go in an independent variable in the render result.
Something like:
render :json => {boats: #boats with all the includes, numTotalBoats: #NumTotalBoats}
I tried thousands of combinations, but or I´m getting syntax errors or none of them is returning the expected result, something like
{boats: [boat1 with all the includes, boat2 with all the includes, ... boatN with all the includes], numTotalBoats: N}
Without adding any gems:
def index
boats = Boat.includes(:year)
render json: {
boats: boats.as_json(include: { year: { only: :name } }),
numTotalBoats: boats.count
}
end
At some point though, I believe you should use stand-alone serializers:
Note: Depending on whether you're using pagination gem or not, you might need to change .count calls below to .total_count (for Kaminari) or something else that will read the count correctly from paginated collection.
I recommend using ActiveModel Serializers and this is how it would be accomplished for your case.
Start by adding the gem to Gemfile:
gem 'active_model_serializers', '~-> 0.10'
Overwrite the adapter in config/initializers/active_model_serializer.rb:
ActiveModelSerializers.config.adapter = :json
Define serializers for your models,
# app/serializers/boat_serializer.rb
class BoatSerializer < ActiveModel::Serializer
attributes :name
has_one :year
end
# app/serializers/year_serializer.rb
class YearSerializer < ActiveModel::Serializer
attributes :name
end
And finally, in your controller:
boats = Boat.includes(:year)
render json: boats, meta: boats.count, meta_key: "numTotalBoats"
And you will achieve:
{
"boats": [
{
"name": "Boaty McBoatFace",
"year": {
"name": "2018"
}
},
{
"name": "Titanic",
"year": {
"name": "1911"
}
}
],
"numTotalBoats": 2
}
Adding that count in each index controller is a bit tedious, so I usually end up defining my own adapters or collection serializers in order to take care of that automatically (Tested with Rails 5, not 4).
# lib/active_model_serializers/adapter/json_extended.rb
module ActiveModelSerializers
module Adapter
class JsonExtended < Json
def meta
if serializer.object.is_a?(ActiveRecord::Relation)
{ total_count: serializer.object.count }
end.to_h.merge(instance_options.fetch(:meta, {})).presence
end
end
end
end
# config/initializers/active_model_serializer.rb
ActiveModelSerializers.config.adapter = ActiveModelSerializers::Adapter::JsonExtended
# make sure to add lib to eager load paths
# config/application.rb
config.eager_load_paths << Rails.root.join("lib")
And now your index action can look like this
def index
boats = Boat.includes(:year)
render json: boats
end
And output:
{
"boats": [
{
"name": "Boaty McBoatFace",
"year": {
"name": "2018"
}
},
{
"name": "Titanic",
"year": {
"name": "1911"
}
}
],
"meta": {
"total_count": 2
}
}
I think it's a little easier to parse this count for different endpoints and you will get it automatically while responding with a collection, so your controllers will be a little simpler.

Rails 5 ActiveRecord, how to include fields from associated tables?

With Rails 5, Given the models:
chef_positions
* id
* name
skills
* id
* name
chef_position_skills
* id
* chef_position_id
* skill_id
I have a controller method to return the chef_position_skills by chef_position_id:
def index
chef_position = ChefPosition.find(params[:chef_position_id])
render json: chef_position.chef_position_skills
end
This returns:
[{"id":1,"chef_position_id":2,"skill_id":1,"created_at":"2017-06-05T15:44:06.821Z","updated_at":"2017-06-05T15:44:06.821Z"},{"id":2,"chef_position_id":2,"skill_id":2,"created_at":"2017-06-05T15:44:06.821Z","updated_at":"2017-06-05T15:44:06.821Z"}]
How can I get the controller to do the following:
include skill.name for each record
Do not include the timestamps
you need to associate the two first if you haven't already, in your model, chef_positions.rb
has_many :skills, through: :chef_position_skills
Then in your controller,
ChefPosition.where(id: params[:chef_position_id]).joins(:skills).select('chef_positions.id, skills.name')
def index
chef_position = ChefPosition.find(params[:chef_position_id])
render json: chef_position.chef_position_skills.map(&:json_data)
end
# ChefPositionSkill#json_data
def json_data
to_json(
include: { skill: { only: [:name] } },
only: [:id, :chef_position_id, :skill_id]
)
end
Define a method json_data (just for convenience), and use .map to call it for each chef_position_skill.
The include and only are standard json serializer methods, which assist rails in what needs to be included.
The only drawback (as far as I see), is that now you will have another attribute "skill": { "name": "skill_name" } in your final json.
Use
render json: chef_position.chef_position_skills.
map {|s| s.slice(:id, :chef_position_id, :skill_id).merge s.skill.slice(:name) }
I don't have the same models but here is a similar example:
irb(main):026:0> u.slice(:id, :email).merge u.funds.slice(:min)
=> {"id"=>1, "email"=>"test#example.com", "min"=>1000000}
But I think you'll really like JBuilder which is included in Rails 5.
https://github.com/rails/jbuilder

Rails, how to specify which fields to output in a controller's JSON response?

in my controller I currently have:
invite = Invite.find_by_token(params[:id])
user = invite.user
json_response({
user: user
})
def json_response(object, status = :ok)
render json: object, status: status
end
Right now, user is returning all user fields. I want to return just (id, email)... I've tried:
user = invite.user.select(:id, :email)
user = invite.user.pluck(:id, :email)
neither works. Ideas?
You can use the method as_json passing attributes you want in the response, like:
user.as_json(only: [:id, :email])
I know this question already has an answer, but there is also a nice gem you could use called active_model_serializers. This lets you specify exactly which properties you want in your JSON output for different models and even let's you include relationships to other models in your response.
Gemfile:
gem 'active_model_serializers', '~> 0.10.0'
Then run bundle install.
You can then create a serializer using the generator command:
rails g serializer user
which will create the serializer in project-root/app/serializers/.
In your serializer, you can whitelist the attributes you would like:
project-root/app/serializers/user_serializer.rb:
class UserSerializer < ActiveModel::Serializer
attributes :id, :email
end
Now any time you return a User object it will only output those two attributes, id and email.
Want to print out related models? Easy. You can just add the relationship in your serializer and it will include those related models in your JSON output.
Pretend a user "has many" posts:
class UserSerializer < ActiveModel::Serializer
attributes :id, :email
has_many :posts
end
Now your JSON outputs should look something like:
{
"id": 1,
"email": "user#example.com",
"posts": [{
id: 1,
title: "My First Post",
body: "This is the post body.",
created_at: "2017-05-18T20:03:14.955Z",
updated_at: "2017-05-18T20:03:14.955Z"
}, {
id: 2,
title: "My Second Post",
body: "This is the post body again.",
created_at: "2017-05-19T20:03:14.955Z",
updated_at: "2017-05-19T20:03:14.955Z"
},
...
]
}
Pretty neat and convenient. And if you want to limit the the posts to only print certain columns as well, all you need to do is create a serializer for posts, specify the attributes, and the output will just work.

Using Ransack in a Rails 5 API only application

I recently started working on a Rails 5 API only application and I included jsonapi-resources as well as ransack to easily filter the results for any given request. By default, jsonapi-resources provides basic CRUD functionality, but in order to insert the search parameters for ransack I need to overwrite the default index method in my controller:
class CarsController < JSONAPI::ResourceController
def index
#cars = Car.ransack(params[:q]).result
render json: #cars
end
end
Now, this works fine, but it no longer uses jsonapi-resources to generate the JSON output, which means the output changed from:
# ORIGINAL OUTPUT STRUCTURE
{"data": [
{
"id": "3881",
"type": "cars",
"links": {
"self": ...
},
"attributes": {
...
}
}]
}
To a default Rails JSON output:
[{
"id": "3881",
"attr_1": "some value",
"attr_2": "some other value"
}]
How can I keep the original output structure while patching the index method in this controller?
Try to use the gem https://github.com/tiagopog/jsonapi-utils. In your case the problem will be solved in this way:
class CarsController < JSONAPI::ResourceController
include JSONAPI::Utils
def index
#cars = Car.ransack(params[:q]).result
jsonapi_render json: #cars
end
end

Resources