【问题标题】:Rails 3.2 Associations and :includeRails 3.2 关联和 :include
【发布时间】:2013-08-31 09:36:06
【问题描述】:

在 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
  }
]

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.2 associations entity-relationship many-to-one


    【解决方案1】:

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

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

    另见:

    【讨论】:

    • 哦!我的问题是针对索引响应,但问题是,所以我将respond_with @posts 替换为:render json: @posts.to_json(:include =&gt; :user) 并且效果很好!非常感谢!
    • 啊,抱歉,过于关注那些渲染,甚至没有看 :respond_to!幸好这是同一类型的问题 :) 很高兴为您提供帮助。
    猜你喜欢
    • 2013-07-01
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    相关资源
    最近更新 更多