【问题标题】:When building a json api for a model with a belongs_to association, the whitelisted attributes of that association are ignored在为具有 belongs_to 关联的模型构建 json api 时,该关联的白名单属性将被忽略
【发布时间】:2013-08-08 17:34:28
【问题描述】:

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

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

/roles/1.json

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

但是,此 json 响应不用于 user#show json 响应。它不断添加created_atupdated_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" } } }

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

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

user.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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activemodel active-model-serializers


    【解决方案1】:

    摘自 ActiveModelSerializer 的 github 页面的 issue queue 中的这位绅士: 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
    

    因此,即使控制器中有 User belongs_to :role 关联,使用 has_one 关联也会利用 ActiveModel 序列化程序并只为我提供我想要的属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多