2014年6月7日 星期六

Active Model Serializers

Active Model Serializers gem link

overriding the as_json method in the model
we can use to fully customize the JSON output

call current_user directly in our serializer

/app/controllers/application_controller.rb
serialization_scope :view_context
/app/serializers/article_serializer.rb
delegate :current_user, to: :scope

Generating JSON Outside JSON Requests

/app/views/articles/index.html.erb
<div id="articles" data-articles="<%= json_for @articles %>">
The helper method to generate the data will look like this:
/app/helpers/application_helper.rb
module ApplicationHelper
  def json_for(target, options = {})
    options[:scope] ||= self
    options[:url_options] ||= url_options
    target.active_model_serializer.new(target, options).to_json
  end
end
It first sets the :scope option for the serializer to self, which is the view context and a :url_options which it is important to pass in so that we don’t get any errors out host option being undefined. Finally we call active_model_serializer on the object that’s being passed in

沒有留言:

張貼留言