Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

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

Closed
KurtRMueller opened this Issue · 2 comments

2 participants

@KurtRMueller

Hello,

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
@franciscodelgadodev

Hello @KurtRMueller have you tried something like

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

has_one :role, serializer: RoleSerializer
end

I think it works.

:) I hope help you.

Cheers xD

@KurtRMueller

Yes, it does. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.