【问题标题】:Rendering json data fields from mysql db in rails response object在rails响应对象中从mysql db渲染json数据字段
【发布时间】:2019-01-13 09:39:17
【问题描述】:

我有一个使用支持 json 字段的 mysql db 5.7 的 rails 4.2 应用程序。所以我的用户模型有一个名为 display_pic 的字段,它是一个 json 对象。

class User < ActiveRecord::Base
    serialize :display_pic, JSON
    ....

在 get_user 操作中,我按如下方式呈现用户

def get_user
  @u = User.where(...)
  render json: { user: @u }
end

问题在于 json 字段 display_pic 没有作为嵌套的 json 对象出现,而是呈现为字符串。我想得到如下回复

{ 
  "user": {
     "name": "some name", 
     "email": "some email",
     "display_pic": {
         "url": "http://someurl.com",
         "width": "400px",
      }
   }
}

【问题讨论】:

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


    【解决方案1】:

    这可能是一种更好的方法,但您可以在序列化程序中将其格式化为 json。

    class UserSerializer < ActiveModel::Serializer
      attribute :name
      attribute :email
      attribute :display_pic
    
      def display_pic
        JSON.parse(object.display_pic)
      end
    end
    

    【讨论】:

    • 可能是最好的解决方案,然而,一个更快的解决方案竟然只是覆盖 as_json。非常感谢您的回答:)
    • 也许你应该同时使用覆盖 as_json 和 super(options.merge(methods: [:display_pic]) 的解决方案
    【解决方案2】:

    您是否尝试过使用 .as_json 方法?

    def get_user
      @u = User.where(...)
      render json: @u.as_json
    end
    

    您应该不需要设置 serialize :display_pic, :JSON,但您可以重载 user.rb 类中的方法,以便在前端自动加载响应引用或方法结果:

    class PlayerCharacter < ApplicationRecord
    
          [...]
          def as_json(options = {})
            super(options.merge(include: [ :reference1, :reference2]).merge(methods: [:method_name1, :method_name2])
          end
    end
    

    编辑: 您可以按如下方式添加 display_pic:

    class PlayerCharacter < ApplicationRecord
    
          [...]
          def as_json(options = {})
            super(options.merge(include: [ :display_pic])
          end
    end
    

    【讨论】:

    • 包括:[:display_pic] 不做这项工作。但是,我喜欢在 as_json 中处理它的想法。 def as_json(options = {}) h = super(options) h[:display_pic] = JSON.parse(display_pic) h end 这完成了工作。谢谢你的回答:)
    【解决方案3】:

    使用以下代码将解决您的问题:

    def get_user
      @u = User.where(...)
      render json: { user: JSON.parse(@u)}
    end
    

    【讨论】:

      猜你喜欢
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 2012-12-12
      • 1970-01-01
      • 2014-07-10
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多