Method: ActiveModel::Serializer#serializable_hash
- Defined in:
- lib/active_model/serializer.rb
#serializable_hash(adapter_options = nil, options = {}, adapter_instance = self.class.serialization_adapter_instance) ⇒ Hash Also known as: to_hash, to_h
associations, similar to how ActiveModel::Serializers::JSON is used in ActiveRecord::Base.
TODO: Include ActiveModel::Serializers::JSON. So that the below is true:
@param [nil, Hash] The same valid passed to `serializable_hash`
(:only, :except, :methods, and :include).
See
https://github.com/rails/rails/blob/v5.0.0.beta2/activemodel/lib/active_model/serializers/json.rb#L17-L101
https://github.com/rails/rails/blob/v5.0.0.beta2/activemodel/lib/active_model/serialization.rb#L85-L123
https://github.com/rails/rails/blob/v5.0.0.beta2/activerecord/lib/active_record/serialization.rb#L11-L17
https://github.com/rails/rails/blob/v5.0.0.beta2/activesupport/lib/active_support/core_ext/object/json.rb#L147-L162
@example
# The :only and :except options can be used to limit the attributes included, and work
# similar to the attributes method.
serializer.as_json(only: [:id, :name])
serializer.as_json(except: [:id, :created_at, :age])
# To include the result of some method calls on the model use :methods:
serializer.as_json(methods: :permalink)
# To include associations use :include:
serializer.as_json(include: :posts)
# Second level and higher order associations work as well:
serializer.as_json(include: { posts: { include: { comments: { only: :body } }, only: :title } })
162 163 164 165 166 167 168 169 |
# File 'lib/active_model/serializer.rb', line 162 def serializable_hash( = nil, = {}, adapter_instance = self.class.serialization_adapter_instance) ||= {} [:include_directive] ||= ActiveModel::Serializer.() cached_attributes = [:cached_attributes] ||= {} resource = fetch_attributes([:fields], cached_attributes, adapter_instance) relationships = resource_relationships(, , adapter_instance) resource.merge(relationships) end |