【问题标题】:Select always returns :id even if it is not included in the callSelect 总是返回 :id ,即使它不包含在调用中
【发布时间】:2019-02-05 00:49:39
【问题描述】:

我使用.select 来选择要返回的字段,我指定了除:id, :created_at and :updated_at 之外的所有字段,无论如何它仍然返回"id": null

我正在使用 Ruby on Rails 5 构建一个 API,像往常一样,字段 :id、:created_at 和 :updated_at 是在运行迁移后创建的,其中 :id 是主键。

当我使用address.select(:name, :region, :province)

我明白了:

[
{
    "id": null,
    "name": "Lorem Ipsum",
    "region": "some text",
    "province": "some more text"
},
{
    "id": null,
    "name": "Lorem Ipsum 1",
    "region": "some text 1",
    "province": "some more text 1"
}
]

但我期待的是:

[
{
    "name": "Lorem Ipsum",
    "region": "some text",
    "province": "some more text"
},
{
    "name": "Lorem Ipsum 1",
    "region": "some text 1",
    "province": "some more text 1"
}
]

希望我的解释已经足够了。

【问题讨论】:

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


    【解决方案1】:

    你可以这样做:

    render json: address.select(:name, :region, :province).to_json(except: :id)
    

    【讨论】:

    • 好主意@AbM。比我的答案简单得多:-)
    • 完美!我做了以下事情: module Response def json_response(object, status = :ok) render json: object, status: status, except: :id end end 并且工作得很好,谢谢!
    【解决方案2】:

    如果您不想检索 id,则应使用 pluck 而不是 select

    Address.pluck(:name, :region, :province)
    

    这将返回一个没有 id 的值数组。我假设你也想要列名,在这种情况下你可以向模型添加一个方法:

    def self.pluck_to_hash(keys)
      pluck(*keys).map{|pa| Hash[keys.zip(pa)]}
    end
    
    # use it with
    Address.pluck_to_hash([:name, :region, :province])
    

    来自https://stackoverflow.com/a/27995494/10987825pluck_to_hash方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-24
      • 1970-01-01
      • 2018-12-02
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      相关资源
      最近更新 更多