我使用.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"
}
]
希望我的解释是不够的。
你可以做:
render json: address.select(:name, :region, :province).to_json(except: :id)
您应该改用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方法