0

我正在使用 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”属性成为条件属性,但它不起作用。

请指导我如何解决它。提前致谢。

4

2 回答 2

0

您访问context但似乎未定义。从文档

传递给序列化程序的记录和任何参数在 Proc 中分别作为第一个和第二个参数可用。

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, params|
    params[:context][:order_detail]
  }
end

您也不需要检查,== true因为参数已经是布尔值。

如果这不起作用,您可以随时在您的 Proc 中添加一个 puts 或调试器来查看 Proc 中发生了什么。

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, params|
    puts record.inspect
    puts params.inspect
    true
  }
end
于 2020-12-10T21:57:29.567 回答
0

查看条件属性的示例,您只需将params其作为第二个参数传递,因此:

在控制器中:

render json: JSONAPI::Serializer.serialize(order_details, { params: { order_detail: true }})

在序列化程序中:

attribute :ordered_data, if: Proc.new { |record, params|
  params[:order_detail]
}
于 2020-12-16T16:11:42.727 回答