1

I am creating a rails 3 backend that consists of RESTful json controllers. E.g. the controllers look something like this:

respond_to :json

def index
  ...
  respond_with resources
end

...

This is consumed by jQuery on the client. Everything is working great.

My next step is to control the JSON so that some properties are not serialized depending on the context. E.g. the owner of the resource gets more properties sent down than someone who only has read access.

I am currently tending towards Draper and using separate decorators for each model based on the user's role.

My problem is that this is generating a lot of boilerplate. I am also currently using cancan for role based authorization.

Can anyone suggest a better method for accomplishing this?

ghempton
  • 7,777
  • 7
  • 48
  • 53

1 Answers1

1

I recommend using ActiveModel::Serializer. See https://github.com/josevalim/active_model_serializers

Create a serializer for each resource you want to expose. You can then separate the serialization logic for each model, easily expose other methods, and scope each model based on roles. It works well with CanCan.

I like this syntax, for example:

class MonkeySerializer < ActiveModel::Serializer
  attributes :name, :mom, :weight

  private

  # use this for a custom attribute not on the model
  def weight
    monkey.weight_in_pounds
  end    
end 
tee
  • 4,149
  • 1
  • 32
  • 44
  • Is there something that you use for the reverse? E.g. deserializing from the client? – ghempton Feb 01 '12 at 03:43
  • see http://stackoverflow.com/questions/1826727/how-do-i-parse-json-with-ruby-on-rails – tee Feb 01 '12 at 05:33
  • Re "It works well with CanCan." - can you elaborate please? I've been trying to serialize permissions (e.g. as can_update), and while I can get at the `scope` (current_user), I cannot find a way to call the `can?` method in the serializer, because I'm not in a controller context. – Jo Liss Jul 25 '12 at 23:06
  • Never mind me, I figured it out and posted it here: http://stackoverflow.com/questions/11660179/serialize-permissions-e-g-cancan-with-active-model-serializers/11660217#11660217 – Jo Liss Jul 25 '12 at 23:38