【问题标题】:Scaffolding in Rails 4 doesn't include id in JSON responseRails 4 中的脚手架在 JSON 响应中不包含 id
【发布时间】:2013-07-06 23:07:48
【问题描述】:

当我在 Rails4 中搭建“客户”时

rails g 脚手架客户名称

JSON 响应不包含“id”

curl http://localhost:3000/customers.json

[{"name":"Test 1","url":"http://localhost:3000/customers/1.json"}]

如何添加“id”?

【问题讨论】:

    标签: json response ruby-on-rails-4


    【解决方案1】:

    如果您使用 gem jbuilder,则会在 views/customers 文件夹中生成文件 index.json.jbuilder

    默认情况下应该是这样的

    json.array!(@customers) do |customer|
      json.extract! customer, :name
      json.url customer_url(customer, format: :json)
    end
    

    只需在第二行添加 :id 即可在 json 响应中看到它

    json.array!(@customers) do |customer|
      json.extract! customer, :name, :id
      json.url customer_url(customer, format: :json)
    end
    

    新的 json 响应将是

    [{"name":"Test 1","id":1,"url":"http://localhost:3000/customers/1.json"}]
    

    【讨论】:

    • 遇到了完全相同的问题。感谢您的自我发帖!
    • 谢谢@moeso,我很高兴能提供帮助:)
    猜你喜欢
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 2020-05-28
    • 1970-01-01
    • 2014-10-07
    • 2015-02-12
    相关资源
    最近更新 更多