1

I'm started using fastjson_api, I have implemented attribute-based control in my project how do reject the attributes when I'm returning the JSON data.
For Example:-
I have a customer table where it has customer name, email, phone, address For some roles, I may give access to phone number and for some, I'll not give them access
not_allowed_attributes = ["phone"]

class CustomerSerializer
  include FastJsonapi::ObjectSerializer
  attributes :name, :email, :phone  
  attribute :phone do |object|
    unless not_allowed_attributes.include?"phone"
      object.phone
    end
  end
end

But It is not a dynamic way of implementing, so whenever there is changed in not_allowed_attributes it should dynamically filter out the attributes from the JSON response.
For role1 not_allowed_attributes = ["email","phone"]
for role2 not_allowed_attributes = ["phone"]

not_allowed_attributes I'll send it in params for the serializer and there is it possible to remove the attributes based on their role.

Rahul
  • 170
  • 1
  • 3
  • 14

1 Answers1

0

You can use the conditional attributes of FastJSONAPI, by passing in a Proc. I'm not exactly clear how your code implements roles, but let's assume you have an admin role and you want to display the phone when the user is an admin. The code below should work for that use case:

class CustomerSerializer
  include FastJsonapi::ObjectSerializer
  attributes :name, :email, :phone  
  attribute :phone, if: Proc.new { |record| record.admin? }
end
Adim
  • 1,716
  • 12
  • 13
  • let say not_allowed_attributes has name and email for other roles again I need to define a block to that attribute, can it be implemented in such a way that it should check and it should attach the attribute otherwise it should not. – Rahul Nov 18 '19 at 12:09
  • Can you show what not_allowed_attributes looks like? – Adim Nov 18 '19 at 12:55
  • Hi nwocha, thanks for the response I have edit the questions, actucally for role1 not_allowed_attributes = ["phone"] and for role2 not_allowed_attributes = ["email"] is it possible to reject attributes in serializer class. – Rahul Nov 19 '19 at 14:39