【问题标题】:Rails: Generate Json response based on conditionRails:根据条件生成 Json 响应
【发布时间】:2018-03-10 02:46:49
【问题描述】:

如何在json.jbuilder 文件中生成基于条件的JSON 响应。 例如:

json.posts @posts do |post|
    post.id post.id
    post.users.each do |user|
        if user.status == true
           json.name user.name
           json.age user.age
        else
           json.name user.supervisor_name
           json.age user.supervisor_age
        end
    end
end

问题是,如果 user.status == false 比它不执行 else 部分。 有人可以帮忙吗?

我想要这样的回应:

{
  "posts": [
    {
      "id": "1",
      {
        "name": "Jhon",
        "age": "24"
      },
      {
        "name": "Wick",
        "age": "25"
      }
    },
    {
      "id": "2",
      {
        "name": "Tom",
        "age": "32"
      },
      {
        "name": "Cruis",
        "age": "31"
      }
    }
  ]
}

【问题讨论】:

    标签: ruby-on-rails json ruby api jbuilder


    【解决方案1】:

    你应该这样做

    json.posts @posts do |post|
      json.id post.id
      json.users post.users do |user|
        if user.status == true
          json.name user.name
          json.age user.age
        else
          json.name user.supervisor_name
          json.age user.supervisor_age
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      • 2020-12-30
      • 2020-12-09
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      相关资源
      最近更新 更多