2012-01-09 23 views
1

我正在創建一個由RESTful json控制器組成的rails 3後端。例如。控制器看起來像這樣:上下文相關的JSON響應

respond_to :json 

def index 
    ... 
    respond_with resources 
end 

... 

這是jQuery在客戶端使用。一切都很好。

我的下一步是控制JSON,以便某些屬性不會根據上下文序列化。例如。資源的所有者獲得的發送的屬性比只有讀取權限的人要多。

我目前正在傾向於Draper並根據用戶的角色爲每個模型使用單獨的裝飾器。

我的問題是,這是產生了很多樣板。我目前也使用cancan進行基於角色的授權。

任何人都可以提出一個更好的方法來完成這個嗎?

回答

1

我推薦使用ActiveModel :: Serializer。請參閱https://github.com/josevalim/active_model_serializers

爲要公開的每個資源創建一個序列化程序。然後,您可以分離每個模型的序列化邏輯,輕鬆地公開其他方法,並根據角色確定每個模型的範圍。它與CanCan運作良好。

我喜歡這種語法,例如:

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 
+0

是否有您使用反向的東西嗎?例如。從客戶端反序列化? – ghempton 2012-02-01 03:43:20

+0

request_hash = ActiveSupport :: JSON.decode(request.body) – tee 2012-02-01 05:33:00

+0

請參閱http://stackoverflow.com/questions/1826727/how-do-i-parse-json-with-ruby-on-rails – tee 2012-02-01 05:33:36