0

2 つのテーブルを関連付けるのに問題があります。投稿できるユーザーがいます

ここに私の移行ファイルがあります:

class LinkUsersAndPosts < ActiveRecord::Migration

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

end

私のモデル:

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

私のコントローラー:

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

投稿は正しく作成され、user_id はすべて正常に設定されています。問題は、ユーザーを含む投稿のリストを取得したい場合です。投稿のリストは取得されますが、ID 以外のユーザーに関するデータはありません。

応答 :

[
  {
    "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
  }
]
4

1 に答える 1