ActiveModelSerializer仅显示关联的ID

时间:2018-12-20 18:05:21

标签: ruby-on-rails ruby active-model-serializers

我正在尝试在我的API中使用ActiveModelSerializer。除了BusinessCategory关系外,其他一切似乎都可以正常工作。它仅显示该ID。我希望它显示所有属性。我不确定它是否还在使用序列化程序,因为当我删除关系时,它仍然会显示。

PerksSerializer

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

PerksController

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

BusinessCategorySerializer

[e for i in range(0, len(l), n+k) for e in l[i:i+n]]
# [4, 3, 5, 8, 12, 2]

1 个答案:

答案 0 :(得分:1)

您可以执行相同的代码,例如:

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