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}
render :json => {boats: @boats, numTotalBoats: @boats.size}active_model_serializersgem? The AMS can be used as PORO, which mean you can get the serializable object beforehand, then passing it torendermethod. You can find the idea from AMS document How to serialize a Plain-Old Ruby Object (PORO) and Using AMS Outside Of A ControllernumTotalBoats:? Is it a model or just a method?