Search code examples
ruby-on-railsjsonrubyapijbuilder

Rails: Generate Json response based on condition


How to generate conditional based JSON response in json.jbuilder file. For example:

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

The problem is, if user.status == false than it doesn't execute the else part. Anyone can help?

I want response something like this:

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

Solution

  • You should do something like this

    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