ruby-on-rails - 如何删除载波自动生成的json

标签 ruby-on-rails carrierwave active-model-serializers

我正在使用 jquery-file-upload 将头像图像文件上传到带有 Rails 的 Carrierwave。

Controller :

class Api::V1::AvatarsController < ApplicationController
  load_and_authorize_resource :user
  load_and_authorize_resource :avatar, through: :user
  respond_to :json

  def create
    @avatar.active = true
    @avatar.save
    respond_with @avatar, location: nil
  end
end

我还使用 active_model_serializers 生成 json:

class AvatarSerializer < ApplicationSerializer
  attributes :active
  attributes :image
  attributes :crop_x
  attributes :crop_y
  attributes :crop_w
  attributes :crop_h

  attributes :image_medium_path
  attributes :image_large_path
  attributes :can_manage

  attributes :user_id

  def image_medium_path
    object.image_url :medium
  end

  def image_large_path
    object.image_url :large
  end

  def can_manage
    Ability.new(scope).can?(:manage, object)
  end
end

使用 jquery-file-upload 上传头像图像后,我得到了响应:

  {"avatar":{
      "id":"51eba3143803f8aa7c000009",
      "active":true,
      *"image":{
        "image":{
          "url":"...",
          "large":{
            "url":"..."
          },
          "medium":{
            "url":"..."
          },
          "small":{
            "url":"..."
          },
          "xsmall":{
            "url":"..."
          },
          "xxsmall":{
            "url":"..."
          }
        }
      },*       "crop_x":0,"crop_y":0,"crop_w":294,"crop_h":294,"image_medium_path":"...","image_large_path":"...","can_manage":true,"user_id":"51e4156a3803f8cde900000b"}}

正如你所看到的,json 的“image”部分是 carriverwave 添加的部分。我想删除它。怎么做?谢谢

最佳答案

我刚刚通过重写 to_json 方法解决了类似的问题。

class MyModel < ActiveRecord::Base
  ...
  def to_json(options = nil)
    params = {field: self.field,... image: self.image.url}
    ActiveSupport::JSON.encode(params, options)
  end
end

关于ruby-on-rails - 如何删除载波自动生成的json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17770763/

相关文章:

ruby-on-rails - 从 Rails 3.2 发送简单邮件时出现段错误

ruby-on-rails - rails : How to reference images in CSS within Rails 4

Carrierwave 将对象数据保存到数据库而不是文件名

ruby-on-rails - 在 Rails 中为多个模型使用一个图像 uploader (载波)?

ruby-on-rails - 如何将参数从 Controller 传递到我的序列化程序?

authentication - Ember-Data + AMS => JSON 或 HTTP header 的 Ember.js 身份验证 token ?

javascript - 在 ember.js 中保存对象时出错 : 'Object X has no method ' save''

ruby-on-rails - Rails 3.2 Carrierwave 预编译错误

ruby-on-rails - RoR 从云迁移到载波

ruby-on-rails - 如何有条件地在 Rails Active Model Serializer v0.8 中包含关联