I'm trying to using an ActiveModelSerializer in my API. Everything seems to work except for the BusinessCategory relationship. It just shows the id for that. I want it to show all the attributes. I'm not sure it's even using the serializer because when I remove the relationship it still shows up.
class PerksSerializer < ActiveModel::Serializer
attributes :id, :status, :scope, :business_name, :business_description, :business_address_street,
:business_address_state, :business_address_city, :business_address_postal_code,
:business_website, :latitude, :longitude, :headline, :description, :start_date, :end_date,
:redemption_instructions, :cashier_instructions, :redemption_button_text, :claim_type,
:business_manager_approved_by, :created_at
belongs_to :primary_business_category
belongs_to :secondary_business_category
end
def index
data = property.available_perks
render json: data
end
class BusinessCategorySerializer < ActiveModel::Serializer
attributes :name, :description
end
You can do the same code like:
class PerksSerializer < ActiveModel::Serializer
attributes :id, :status, :scope, :business_name, :business_description, :business_address_street,
:business_address_state, :business_address_city, :business_address_postal_code,
:business_website, :latitude, :longitude, :headline, :description, :start_date, :end_date,
:redemption_instructions, :cashier_instructions, :redemption_button_text, :claim_type,
:business_manager_approved_by, :created_at, :primary_business_category,:secondary_business_category
def primary_business_category
BusinessCategorySerializer.new(object.primary_business_category)
end
def secondary_business_category
BusinessCategorySerializer.new(object.secondary_business_category)
end
end
or
belongs_to :primary_business_category, serializer: BusinessCategorySerializer
belongs_to :secondary_business_category, serializer: BusinessCategorySerializer
Check if your PerksSerializer is called, if not:
def index
data = property.available_perks
render json: data, each_serializer: PerksSerializer
end