我正在使用 ruby-2.6.0 和 Rails 6 开发 Ruby on Rails 项目。我正在开发 api 部分,我在我的应用程序中使用了 jsonapi-serializers gem。我想在序列化程序中添加条件属性。
控制器:
class OrderDetailsController < Api::V1::ApiApplicationController
before_action :validate_token
def show
user = User.find_by_id(@user_id)
order_details = user.order_details.where(id: params[:id])&.first
render json: JSONAPI::Serializer.serialize(order_details, context: { order_detail: true })
end
end
序列化器:
class OrderDetailSerializer
include JSONAPI::Serializer
TYPE = 'Order Details'
attribute :order_number
attribute :price
attribute :quantity
attribute :order_status
attribute :ordered_date, if: Proc.new { |record|
context[:order_detail] == true
}
end
所以在这里我从上下文中的控制器传递'order_detail'。我收到以下错误: -
TypeError (#<Proc:0x00007fe5d8501868@/app_path/app/serializers/order_detail_serializer.rb:46> is not a symbol nor a string):
我遵循了jsonapi-serializer中提到的条件属性,并试图使我的“ordered_date”属性成为条件属性,但它不起作用。
请指导我如何解决它。提前致谢。