0

I am looking to use active model serialize on a model called roles, which spits back the roles and that roles permissions. How ever, I want to tell Active Model Serializer that if the role name is Administrator you should never include it in the json of roles returned.

So if I do a show or a index action on roles through an api call, I should never see Administrator in the returned result.

Right now this is all I have for role serialize:

class RoleSerializer < ActiveModel::Serializer
  attributes :id, :role
end

Would I do it here or in the controller for index and show? and if so what would I do?

user3379926
  • 3,855
  • 6
  • 24
  • 42

1 Answers1

0

The job of an Active Model serializer is not to select which records should and should not be returned in the json. For this you want to use a scope or at least a where statement.

You could probably also skip the custom serializer, and just pass the attributes you want to to_json.

class Role < ActiveRecord::Base

  scope :without_adminstrators, -> { where('role <> "Administrator"') }

end

class RolesController < ApplicationController

  def non_administrator
    Role.without_adminstrators.to_json(only: [:id, :role])
  end

end
Douglas F Shearer
  • 25,952
  • 2
  • 48
  • 48
  • Could I add to the index, for example: `@roles = Roles.where.not(name: 'Administrator')` and then use the serialize as intended? and then do something similar for the show? – user3379926 May 08 '14 at 21:39