mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-23 06:16:50 +00:00
If the `id` attribute for a class isn't taken directly from the object when
serializing it, it may be desirible for other classes that serialize a
relationship with that class to overwrite the relationship IDs they serialize.
For example, suppose we have:
```(ruby)
class Repo < Model
attributes :id, :github_id, :name
associations :configs
end
class Config < Model
attributes :id
belongs_to :repo
end
class RepoSerializer < ActiveModel::Serializer
attributes :id, :name
has_many :update_configs
def id
object.github_id
end
end
class ConfigSerializer < ActiveModel::Serializer
attributes :id
belongs_to :repo
end
```
In the above example, serializing a list of `Repo`s will give the `github_id`
for each one, but serializing a `Config` will give the `id` for its parent repo.
Ideally AMS would inspect the `RepoSerializer` when serializing the `Config`,
and realise it can't just output the foreign key. Unfortunately, getting the
serialization class for the child repo currently requires loading the record
(via evaluating `lazy_assocation`), and loses the performance benefit of the
existing `belongs_to?` path. Instead, I've opted to use
`read_attribute_for_serialization` instead of `object.send` to fetch the
serialized foreign key. This allows the serialized relationship ID to be
overwritten using
```(ruby)
class ConfigSerializer < ActiveModel::Serializer
...
def repo_id
object.repo.github_id
end
end
```
|
||
|---|---|---|
| .. | ||
| action_controller | ||
| active_model_serializers | ||
| adapter | ||
| benchmark | ||
| fixtures | ||
| generators | ||
| serializers | ||
| support | ||
| active_record_test.rb | ||
| adapter_test.rb | ||
| array_serializer_test.rb | ||
| cache_test.rb | ||
| collection_serializer_test.rb | ||
| grape_test.rb | ||
| lint_test.rb | ||
| logger_test.rb | ||
| poro_test.rb | ||
| serializable_resource_test.rb | ||
| test_helper.rb | ||