如何在 json 响应中包含子对象

How to include sub-object in json response

您好,我正在尝试在呈现 json 执行 User.all 时包含用户的角色 我在 rails 和 Mongoid

上使用 ruby

我的回复中只得到 role_id...

role_id":"56cb596bc226cb5c04efd1cb

用户模型:

class User
  include Mongoid::Document
  include ActiveModel::SecurePassword

  has_many :role
  belongs_to :store
  has_many :orders

榜样:

class Role
  include Mongoid::Document

  belongs_to :user

  field :name, type: String
  field :active, type: Mongoid::Boolean

我得到的回应:

    {"_id":"...","api_key":"...","email":"jesus@drinkz.io","name":"... Garcia","password_digest":"...","promotion_ids":[],
"role_id":"56cb596bc226cb5c04efd1cb"}

我如何得到响应:GET /api/v1/users

def index
    @user = User.first
    respond_with @user
  end

如何在响应中嵌入角色?

如果不包括角色,您将获得仅代表用户的 JSON。您可以执行以下操作

def index
  @user = User.first
  respond_with(@user, :include => :role)
end

老派的方式是,

def index
  @user = User.first
  respond_to do |format|
    format.json { render :json => @user.to_json(:include => :role) }
  end
end

将 gem 'active_model_serializers' 添加到您的 gem 文件中(如果您尚未使用它)。然后使用

生成一个用户序列化器
rails generate serializer user

然后将以下内容添加到 app/serializers/user_serializer.rb 文件。

class UserSerializer < ActiveModel::Serializer
  attributes :id, :email,:name, :password_digest, :promotion_ids, :api_key
  has_many :roles
end