2

我正在为我的模型构建一个 json api,User以及一个User belongs_to :role. 即使我已经为Role我想要包含的属性构建了一个 json api 并将其列入白名单,但每当我访问一个user#show操作时,白名单中的属性都会被忽略。

在我的RoleSerializer文件中,我指定只能访问两个属性::id:name. 当我转到“roles#show”操作时,它工作正常并且只呈现这两个属性。

/roles/1.json

{"role":{"id":1,"name":"Admin"}}

但是,此 json 响应不用于user#showjson 响应。它不断添加我不想要的created_atand属性。updated_at

/users/1.json

{ 
  "user": { 
      "id": 1,
      "email": "dietz.72@osu.edu",
      "name_n": "dietz.72", 
      "first_name": "Peter", 
      "last_name": "Dietz",
      "role": {  
          "created_at": "2013-08-08T00:21:56Z",
          "id":1,
          "name": "Admin",
          "updated_at": "2013-08-08T00:21:56Z" } } }

我尝试了多种列出:role属性的方法,user_serializer.rb包括下面的代码。不幸的是,这不起作用。

user_serializer.rb

class UserSerializer < ActiveModel::Serializer
  attributes :id, :email, :name_n, :first_name, :last_name

  # I also tried attributes :role
  attribute :role, serializer: RoleSerializer
end

users_controller.rb - 显示动作

def show
  @user = User.where(id: params[:id]).first

  respond_to do |format|
    format.html
    format.json { render json: users }
  end
end

用户.rb

class User < ActiveRecord::Base
  attr_accessible :email, :emplid, :name_n, :first_name, :last_name

  belongs_to :role
  has_many :agreements, foreign_key: "student_id"
  has_many :forms, through: :agreements, foreign_key: "student_id"

  def active_model_serializer
    UserSerializer
  end
  ...
end
4

1 回答 1

0

Taken from this fine gentleman from the issue queue of ActiveModelSerializer's github page: https://github.com/rails-api/active_model_serializers/issues/371#issuecomment-22363620

class UserSerializer < ActiveModel::Serializer
  attributes :id, :email, :name_n, :first_name, :last_name

  has_one :role, serializer: RoleSerializer
end

So, even though there is a User belongs_to :role association in the controller, using has_one association utilizes the ActiveModel Serializer and gives me only the attributes I want.

于 2013-08-08T23:18:19.757 回答