简体   繁体   English

Rails 3.2关联和:include

[英]Rails 3.2 Associations and :include

I have some troubles to make an association between 2 tables. 我很难在2个表之间建立关联。 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. 帖子已正确创建,将user_id设置为all即可。 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. 问题是当我想检索包括用户的帖子列表时,帖子列表已检索到,但是除了他的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
  }
]

By default a JSON response won't return any associated models. 默认情况下,JSON响应不会返回任何关联的模型。 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: 另请参阅:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM