ActiveModelSerializer показывает только идентификатор для ассоциации - PullRequest
0 голосов
/ 20 декабря 2018

Я пытаюсь использовать ActiveModelSerializer в моем API.Кажется, все работает, за исключением отношений BusinessCategory.Это просто показывает идентификатор для этого.Я хочу, чтобы он показал все атрибуты.Я не уверен, что он даже использует сериализатор, потому что когда я удаляю связь, он все равно обнаруживается.

PerksSerializer

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

PerksController

  def index
    data = property.available_perks
    render json: data
  end

BusinessCategorySerializer

class BusinessCategorySerializer < ActiveModel::Serializer
  attributes :name, :description
end

1 Ответ

0 голосов
/ 20 декабря 2018

Вы можете сделать тот же код, например:

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

или

belongs_to :primary_business_category, serializer: BusinessCategorySerializer

belongs_to :secondary_business_category, serializer: BusinessCategorySerializer

Проверьте, вызывается ли ваш PerksSerializer, если нет:

 def index
   data = property.available_perks
   render json: data, each_serializer: PerksSerializer
 end
...