Question

I have some troubles to make an association between 2 tables. I have Users who can write Posts

Here is my migration file :

class LinkUsersAndPosts < ActiveRecord::Migration

  def change
    add_column :posts, :user_id, :integer
    add_index  :posts, :user_id
  end

end

My models :

class Post < ActiveRecord::Base
  attr_accessible :content, :title
  belongs_to :user
end

class User < ActiveRecord::Base
  attr_accessible :email, :login, :password, :password_confirmation, :rights
  has_many :posts
end

My controller :

class PostsController < ApplicationController
   respond_to :json

   def index
     @posts = Post.includes(:user).all
     respond_with @posts
   end

   def create
     @post = Post.new(params[:post])
     @post.user = current_user

     if @post.save
       render json: @post, status: :created, location: @post
     else
       render json: @post.errors, status: :unprocessable_entity
     end
  end
end

The posts is correctly created, the user_id is set all is fine. The problem is when i want to retrieve the list of posts including user, the list of posts is retrieve, but i havn't any data on the user except his id.

Response :

[
  {
    "content":"jksdjd",
    "created_at":"2013-08-31T09:03:01Z",
    "id":11,"title":"kdjs",
    "updated_at":"2013-08-31T09:03:01Z",
    "user_id":4
  },
  {
    "content":"tez2",
    "created_at":"2013-08-31T09:16:45Z",
    "id":12,
    "title":"test2",
    "updated_at":"2013-08-31T09:16:45Z",
    "user_id":4
  }
]
Was it helpful?

Solution

By default a JSON response won't return any associated models. You need to specify the other models you want returned. So in your case, you can do this:

render json: @post =>  @post.to_json(:include => :user), status: :created, location: @post

Also see:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top