【问题标题】:Rails Adding Attributes to JSON SerializerRails 向 JSON 序列化器添加属性
【发布时间】:2021-03-28 16:39:31
【问题描述】:

我有一个应该呈现为 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}

但是如何使用序列化器来获得相同的结果呢?

【问题讨论】:

    标签: ruby-on-rails ruby serialization to-json


    【解决方案1】:

    把to_json改成as_json,合并新的key-value。

    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
    

    【讨论】:

      【解决方案2】:

      我更喜欢使用一些序列化 gem 来处理序列化过程,例如

      jsonapi-serializer https://github.com/jsonapi-serializer/jsonapi-serializer

      【讨论】:

        【解决方案3】:
        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)

        如果留空,它仍然会像您发布的原始课程一样运行

        【讨论】:

          猜你喜欢
          • 2010-10-15
          • 1970-01-01
          • 1970-01-01
          • 2011-04-03
          • 2018-08-19
          • 1970-01-01
          • 1970-01-01
          • 2016-01-07
          • 1970-01-01
          相关资源
          最近更新 更多