Rails 向 JSON 序列化程序添加属性

Rails Adding Attributes to JSON Serializer

我有一个模型应该呈现为 JSON,为此我使用了序列化器

class UserSerializer
  def initialize(user)
    @user=user
  end

  def to_serialized_json
    options ={
      only: [:username, :id]
    }

    @user.to_json(options)
  end
end

当我 render json: 我想添加一个 JWT 令牌和一个 :errors。不幸的是,我很难理解如何向上面的序列化程序添加属性。以下代码不起作用:

def create
    @user = User.create(params.permit(:username, :password))
    @token = encode_token(user_id: @user.id) if @user     
    render json: UserSerializer.new(@user).to_serialized_json, token: @token, errors: @user.errors.messages
end

此代码仅呈现 => "{\"id\":null,\"username\":\"\"}",我如何添加属性 token:errors: 以便呈现类似这样的内容但仍使用序列化程序:

{\"id\":\"1\",\"username\":\"name\", \"token\":\"eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxfQ.7NrXg388OF4nBKLWgg2tdQHsr3HaIeZoXYPisTTk-48\", \"errors\":{}}

我可以使用

render json: {username: @user.username, id: @user.id, token: @token, errors: @user.errors.messages}

但是如何使用序列化程序获得相同的内容?

将 to_json 更改为 as_json,并合并新的键值。

class UserSerializer
  def initialize(user, token)
    @user=user
    @token=token
  end

  def to_serialized_json
    options ={
      only: [:username, :id]
    }

    @user.as_json(options).merge(token: @token, error: @user.errors.messages)
  end
end

我更喜欢使用一些序列化 gem 来处理像

这样的序列化过程

jsonapi-序列化器 https://github.com/jsonapi-serializer/jsonapi-serializer

或等等

class UserSerializer
  def initialize(user)
    @user=user
  end

  def to_serialized_json(*additional_fields)
    options ={
      only: [:username, :id, *additional_fields]
    }

    @user.to_json(options)
  end
end

每次你想添加新的更多字段进行序列化时,你可以做类似 UserSerializer.new(@user).to_serialized_json(:token, :errors)

的事情

如果留空,它将使用默认字段:id, :username

如果您希望添加的 json 可自定义

class UserSerializer
  def initialize(user)
    @user=user
  end

  def to_serialized_json(**additional_hash)
    options ={
      only: [:username, :id]
    }

    @user.as_json(options).merge(additional_hash)
  end
end

UserSerializer.new(@user).to_serialized_json(token: @token, errors: @user.error.messages)

如果保留为空,它的行为仍与您发布的原始 class 相同