【问题标题】:ActiveModel Serializer not working for functionActiveModel 序列化程序无法正常工作
【发布时间】:2018-07-04 16:16:35
【问题描述】:

我在我的 Rails API 中使用了ActiveModelSerialziers,它的工作原理就像一个魅力,但我的 1 个函数似乎覆盖了它,并且只返回我的模型(没有任何关联)。如果调用不同的函数,相同的模型会正确返回。

  def getClient
    type = params[:type]

    if type == 'user'
      @client = Client.find_by(user_id: params[:id])
    else
      @client = Client.find_by(id: params[:id])
    end


    render json: { success: true, response: @client }
  end

只返回没有关联的client,序列化器是:

class API::ClientSerializer < ActiveModel::Serializer

    attributes :name, :age, :address

    belongs_to :user
    has_many :check_ins
    has_many :client_docs
    has_many :payments
end

当调用以下函数时,同一模型 (Client) 会正确返回(带有关联):

  def show
    model_name = params[:model].classify
    item = model_name.constantize.find_by(id: params[:id])

    render json: item, status: :ok
  end

为什么会发生这种情况?

【问题讨论】:

  • 试试这个render json: { success: true, response: ActiveModelSerializers::SerializableResource.new(@client, serializer: ClientSerializer }
  • 行得通!但是为什么我需要指定
  • 你是通过 `Client.find_by(user_id: params[:id])` 找到的吗?
  • 在这种情况下,是的。这会导致它吗?
  • 是的。我的代码能解决您的问题吗?

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


【解决方案1】:

您在 rander 语句中缺少适配器::json:

render json: item, adapter: :json, status: :ok

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    相关资源
    最近更新 更多