【问题标题】:Rails 4 json return on APIRails 4 json 返回 API
【发布时间】:2013-10-29 21:51:05
【问题描述】:

我正在我的应用程序上创建一个 API。我目前在我的模型中覆盖了as_json 方法,以便能够从 Paperclip 获取附件和徽标:

def as_json( options = {} )
  super.merge(logo_small: self.logo.url(:small), logo_large: self.logo.url(:large), taxe: self.taxe, attachments: self.attachments)
end

然后在我的控制器中,我正在做:

def index
  @products = current_user.products
  respond_with @products
end

def show
  respond_with @product
end

问题是在索引上,我不想得到所有的附件。我只需要在 show 方法上使用它。所以我试了一下:

def index
  @products = current_user.products
  respond_with @products, except: [:attachments]
end

但不幸的是,它仅适用于默认产品属性(我合并的所有内容似乎都没有考虑在内)。不发送:attachments怎么办?

谢谢

【问题讨论】:

    标签: ruby-on-rails json api return


    【解决方案1】:

    我建议你看看active_model_serializers。它将提供一种很好的 OOP 方式来处理您需要的对象装饰类型 - 选择性地排除属性 - 等等。甚至还有Railscast

    【讨论】:

    • 谢谢。确实,使用它可以使其更加灵活。但是,我仍然没有找到发送关联的方法,无论我是在 index 还是 show 操作本身,因为序列化程序总是发送相同的数据。我所能做的就是根据用户级别发送。有什么想法吗?
    • 两个建议:A) 创建两个不同的序列化器,每个用例一个,并在控制器中选择它,如render json: @objects, each_serializer: ObjectWithAssociationSerializer, status: 200。 B) 在 gem 上查看这个问题:github.com/rails-api/active_model_serializers/issues/331。它在过去帮助过我一个类似的用例。
    • 非常感谢。听起来像是我的问题的一个可能的解决方案,直到它得到 gem 的完全支持。会深入研究的:)谢谢队友
    猜你喜欢
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 2014-04-29
    • 2014-06-13
    • 2019-08-06
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    相关资源
    最近更新 更多