简体   繁体   中英

Context-Sensitive JSON Response

I am creating a rails 3 backend that consists of RESTful json controllers. Eg 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. Eg 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?

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM