Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails 3.2关联和:包括_Ruby On Rails_Ruby On Rails 3.2_Associations_Entity Relationship_Many To One - Fatal编程技术网

Ruby on rails Rails 3.2关联和:包括

Ruby on rails Rails 3.2关联和:包括,ruby-on-rails,ruby-on-rails-3.2,associations,entity-relationship,many-to-one,Ruby On Rails,Ruby On Rails 3.2,Associations,Entity Relationship,Many To One,我很难在两个表之间建立关联。 我有可以写文章的用户 这是我的迁移文件: class LinkUsersAndPosts < ActiveRecord::Migration def change add_column :posts, :user_id, :integer add_index :posts, :user_id end end 默认情况下,JSON响应不会返回任何关联的模型。您需要指定要返回的其他模型。因此,在您的情况下,您可以这样做: rende

我很难在两个表之间建立关联。 我有可以写文章的用户

这是我的迁移文件:

class LinkUsersAndPosts < ActiveRecord::Migration

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

end

默认情况下,JSON响应不会返回任何关联的模型。您需要指定要返回的其他模型。因此,在您的情况下,您可以这样做:

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


哦!我的问题是关于索引响应,但问题是,因此我将
respond_替换为@posts
by:
render json:@posts.to_json(:include=>:user)
,效果很好!非常感谢你!啊,对不起,太关注那些渲染了,甚至没有看:回复!幸好这是同一类问题:)很乐意帮忙。
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
[
  {
    "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
  }
]
render json: @post =>  @post.to_json(:include => :user), status: :created, location: @post