When building a json api for a model with a belongs_to association, the whitelisted attributes of that association are ignored

StackOverflow https://stackoverflow.com/questions/18132411

Question

I'm building a json api for my model, User and a User belongs_to :role. Even though I have already build a json api for Role and whitelisted the attributes I wanted to include, the whitelisted attributes are ignored whenever I visit a user#show action.

In my RoleSerializer file, I have specified that only two attributes can be accessed: :id, and :name. When I go to the 'roles#show' action, this works fine and renders only these two attributes.

/roles/1.json

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

However, this json response is not used for the user#show json response. It keeps tacking on the created_at and updated_at attribute, which I don't want.

/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" } } }

I've tried multiple ways of listing the :role attribute in user_serializer.rb including the following code below. Unfortunately, this does not work.

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 - show action

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
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top