2016-07-20 3 views
0

私はSinatraで書かれたアプリケーションのバックエンドで作業しています。 "/ notifications"というルートを持っていますsinatraアプリケーションでカスタムシリアライザを呼び出す方法

JSONのすべての通知をレンダリングします。 jsonの構造を変更してカスタムシリアライザを書きましたが、今は失敗しています。私が手 エラーは、私が通知シリアライザを選択し、Webサービス/ notification.rb と呼ばれるファイルを持っている

"{"message":"undefined method `read_attribute_for_serialization' for nil:NilClass"}" 

です。 コードは、この

serializer = NotificationSerializer 
json serialize(notifications, root: :notifications, each_serializer: serializer) 

NotificationSerializerは、このようなものであるようなものです。

class NotificationSerializer < Serializer 
    attributes :id, :tag, :event, :time, :read 

    has_one :reference, polymorphic: true, include: true 

ここでの参照は多くのことがあります。

通知モデルが参照で今、すべてのこれらのモデルの

def reference 
company || contact || deal || invitation || meeting || todo || reference_email || reference_user || 
contact_import_job 
    end 

などの基準を定義するには、そこにシリアライザは、私は限られた情報をレンダリングれるこれらのすべてのカスタムシリアライザを作りたいディレクトリシリアライザ/ * で実装しています。 参照内にカスタムシリアライザを呼び出す方法はありますか。

私は通知のためのカスタムシリアライザを書いて、私のrefernce関数内でこのように呼びました。

...|| UserNotificationSerializer.new(reference_user) || ... 

しかし、他のモデルでも同じことをすると、上記のエラーが発生します。 私のカスタムシリアライザを呼び出す正しい方法は何でしょうか。その後、

class Notification < ActiveRecord::Base 
    def public_attributes # or call it whatever 
    attributes_hash = attributes 
    # in activerecord, the attributes method turns a model instance into a hash 
    # do some modifications to the hash here 
    return attributes_hash 
    end 
end 

あなたは、コントローラにJSONを返すしていると言う:

答えて

0

それを行うための良い方法は、モデルのインスタンスメソッドを書くことです

get '/some_route' do 
    @notifications = Notification.all # or whatever 
    serialized_notifications = @notifications.map(&:public_attributes) 
    # For a single record, you could do @notification.public_attributes 
    json_data = serialized_notifications.to_json # a serialized array of hashes 
    content_type :json 
    return json_data 
end 
関連する問題