【问题标题】:rails : How to omit a particular property from an array of objects in a JSON response?rails:如何在 JSON 响应中从对象数组中省略特定属性?
【发布时间】:2016-07-04 16:14:31
【问题描述】:

我一直在尝试获取不包含id column 的模型。我认为select 方法允许这样做,但是当我访问模型时,我看到id 字段带有nil 值。

当我使用时:

module API
  class MyController < ActionController::API
    def index
      response = MyModel
                 .where("value > ?", 0)
                 .select('code','value')
      render json: response, status: 200
    end

当我像这样使用每个检查结果时

我的模特 .where("值 > ?", 0) .select('代码','值') .每个{|m|放 m}

我明白了

<MyModel id: nil, code: "110", value: 100>
<MyModel id: nil, code: "111", value: 100>
<MyModel id: nil, code: "112", value: 100>

在我的回复中,我得到了这个:

[{id: null, code: "110", value: 100},{id: null, code: "111", value: 100},{id: null, code: "112", value: 100}]

如何省略id列?

【问题讨论】:

  • 你为什么要这样做?你想解决什么问题?
  • @jordan 我需要返回一个 MyModel 数组,但不包含 id 字段
  • 对,你已经说了这么多。但是你想解决什么问题?你想“返回一个数组”,但是到哪里呢?用例是什么?您已经成功地从数据库中仅选择了codevalue 字段,这就是id 属性为nil 的原因。
  • 我编辑了我的问题
  • 你没有真正回答我的任何问题。然而,这可能是一个将作为 JSON 响应发送的哈希吗?您是在问如何在 JSON 响应中从对象数组中省略特定属性?

标签: ruby-on-rails ruby rails-activerecord


【解决方案1】:

我相信这与puts 命令有关。如果你只做Model.select(:attributes),如果它不在列表中,它不应该返回 id 列(在这里做了测试并且工作正常)。我相信 puts 命令从数据库或类似的东西中检索对象。顺便说一句,如果你重写了对象类中的to_s方法,你可以重写puts object时打印的内容

【讨论】:

  • 这不是答案。
【解决方案2】:

在Rails中,当使用#select方法时,即使你没有在select方法参数中使用id,它也会显示出来,因为在Rails中默认主键是id。如果您将主键覆盖为其他内容,它将显示该列。看例子:

Coupon.select(:active)
# Coupon Load (0.6ms)  SELECT "coupons"."active" FROM "coupons"
# => #<ActiveRecord::Relation [#<Coupon active: true, code: nil>, #<Coupon active: true, code: nil>...

这是因为在我的优惠券模型中,我将主键设置为 code

class Coupon < ActiveRecord::Base
  self.primary_key = 'code'
  # ..
end

虽然它显示在 inspect 结果中,但直到您真正获取它时它才出现。现在,如果您设置self.primary_key = '' 进行测试,您将看到#select 没有显示任何内容。但是不要像我从select 结果中删除id 显示那样将primary_key 设置为''。我只是想展示它的来源,没有别的。

Coupon.select(:active).order(:active)
# Coupon Load (2.8ms)  SELECT "coupons"."active" FROM "coupons"  ORDER BY "coupons"."active" ASC
# => #<ActiveRecord::Relation [#<Coupon active: true>, #<Coupon active: true>...

【讨论】:

  • 问题是我在应用程序中需要这个主键,但在这种特定情况下,我需要返回和数组与 where 条件,但这个结果不包括 id 字段
  • @GonzaloPincheiraArancibia 它只是在检查中显示id,但实际结果没有id值。
猜你喜欢
  • 2017-08-18
  • 1970-01-01
  • 2019-05-17
  • 2019-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多