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