mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 22:06: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 | ||
| active_model_serializers | ||
| generators/rails | ||
| grape | ||
| tasks | ||
| active_model_serializers.rb | ||