Reputation: 343
I have this code that renders a variable vacancy with a custom serializer and also is included a restaurant as part of my model.
vacancy = Vacancy.find(params[:id])
render json: vacancy,
serializer: VacancyDetailSerializer,
include: [:restaurant]
The thing is that I want to include multiple objects and render, something like this:
vacancy = Vacancy.find(params[:id])
render json: vacancy,
serializer: VacancyDetailSerializer,
include: [:restaurant, :total_vacancies]
In :total_vacancies
I want to send Vacancy.count
, but I don't know if I have to make it by serializers, or in the include, or how to do it.
As I know, I just only need to put a comma after the object and then specify the other object in the included but is not working.
Update
P.D. total_vacancies is not a table, is a method from my model of Vacancy
P.D.2. it's true that if I put total_vacancies
as an attribute in my serializer will work, but if I do that everytime I render this json it will repeat the total_vacancies
every time I call a vacancy, for example, imagine that I have 100 vacancies, then my json will write all the parameters that I have from my vacancy and the total_vacancies
100 times instead of 1 time as a different object
Upvotes: 1
Views: 1351
Reputation: 343
Solution given by Ian Lewis on Facebook:
Just simply put
render json: { vacancy: vacancy, vacancy_count: Vacancy.count }
And then everything works perfectly, the final code was like this:
render json: { vacancy: vacancy, vacancy_count: Vacancy.count },
each_serializer: VacancyDetailSerializer,
include: [:restaurant]
Source:
Upvotes: 0
Reputation: 773
I assume TotalVacancies is another table.
You need to have separate serializer for each one and VacancyDetailSerializer
must be modified like below
if TotalVacancies is not a separate table. If TotalVacancies is not a separate table then use the has_many
which i commented below and use its corresponding Serializer: TotalVacanciesSerializer
class VacancyDetailSerializer < ActiveModel::Serializer
attributes :total_vacancies
#has_many :total_vacancies
has_one :restaurant
def total_vacancies
self.object.count
end
end
# total_vacancies_serializer.rb
class TotalVacanciesSerializer < ActiveModel::Serializer
end
# restaurant_serializer.rb
class RestaurantSerializer < ActiveModel::Serializer
end
You dont need to include like this in render. Since we have added in VacanciesSerializer below code should itself include TotalVacancies and Restaurant
Also you can control the list of attributes in Restaurant and TotalVacancies
vacancy = Vacancy.find(params[:id])
render json: vacancy,
serializer: VacancyDetailSerializer
Upvotes: 1