即使在通话中不包括它的ID:选择总是返回

问题描述 投票:1回答:2

我使用.select选择我想返回现场,我指定除了:id, :created_at and :updated_at各个领域,反正它仍返回"id": null

我建设使用Ruby的API on Rails的5,像往常一样字段: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
2个回答
2
投票

你可以做:

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

1
投票

您应该改用pluck select的,如果你不想要检索的ID。

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])

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

© www.soinside.com 2019 - 2024. All rights reserved.