title: Rails API: Adding array of objects to json return
body: <p>I'm using the built-in API with Rails 5.</p>
  
  <p>I'm learning to write APIs with Rails and I'm trying to figure out how to add a property to my json return that is an array of objects.</p>
  
  <p>I've got a model for Users and Posts.</p>
  
  <p>What I would like to do is return all the posts associated with a users.</p>
  
  <p>What I've done is in posts_controller.rb I've got a method that gets the userID form the URL and returns json that looks like:</p>
  
  <p><code>
  [{"id":1,"content":"My first post!","user":{"id":1,"firstname":"Jody","lastname":"White","email":"t@t.com","fullname_firstname_first":"Jody White"}},{"id":2,"content":"Rails School is awesome!","user":{"id":1,"firstname":"Jody","lastname":"White","email":"t@t.com","fullname_firstname_first":"Jody White"}}]
  </code></p>
  
  <p>But what I want is to return that looks like this:</p>
  
  <pre><code>{
      firstname: "Jody",
      lastname: "White",
      email: "whatever",
      posts: [{
          "id":1,"content":"My first post!"
          },
          {
              "id":2,"content":"Rails School is awesome!"
          }
      ]
  }
  </code></pre>
  
  <p>How do I go about, or can I, getting the data to return like that?</p>
  
  <p>user.rb model</p>
  
  <pre><code>class User &lt; ApplicationRecord
    attr_accessor :fullname_firstname_first
  
    has_many :posts
  
    def fullname_firstname_first
      fullname_firstname_first = firstname + " " + lastname
    end
  end
  </code></pre>
  
  <p>post.rb model</p>
  
  <pre><code>class Post &lt; ApplicationRecord
    belongs_to :user
  end
  </code></pre>
  
  <p>users_controller.rb</p>
  
  <pre><code>class UsersController &lt; ApplicationController
    before_action :set_user, only: [:show, :update, :destroy]
  
    # GET /users
    def index
      @users = User.all
      render json: @users, include: :posts
    end
  
    # GET /users/1
    def show
      @user = User.find(params[:id])
      render json: @user, include: :posts
    end
  end
  </code></pre>