Skip to content

Commit 982fe26

Browse files
authored
Merge pull request #2120 from bf4/allow_customizing_relation_foreign_key
Document new reflection options; support :foreign_key [ci skip]
2 parents af5e9d6 + ec7b585 commit 982fe26

File tree

2 files changed

+7
-1
lines changed

2 files changed

+7
-1
lines changed

docs/general/serializers.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,10 @@ Where:
6464
- `unless:`
6565
- `virtual_value:`
6666
- `polymorphic:` defines if polymorphic relation type should be nested in serialized association.
67+
- `type:` the resource type as used by JSON:API, especially on a `belongs_to` relationship.
68+
- `class_name:` used to determine `type` when `type` not given
69+
- `foreign_key:` used by JSON:API on a `belongs_to` relationship to avoid unnecessarily loading the association object.
70+
- `namespace:` used when looking up the serializer and `serializer` is not given. Falls back to the parent serializer's `:namespace` instance options, which, when present, comes from the render options. See [Rendering#namespace](rendering.md#namespace] for more details.
6771
- optional: `&block` is a context that returns the association's attributes.
6872
- prevents `association_name` method from being called.
6973
- return value of block is used as the association value.

lib/active_model/serializer/reflection.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ class Serializer
99
# @example
1010
# class PostSerializer < ActiveModel::Serializer
1111
# has_one :author, serializer: AuthorSerializer
12+
# belongs_to :boss, type: :users, foreign_key: :boss_id
1213
# has_many :comments
1314
# has_many :comments, key: :last_comments do
1415
# object.comments.last(1)
@@ -58,12 +59,13 @@ def initialize(*)
5859
class_name = options.fetch(:class_name, name.to_s.camelize.singularize)
5960
class_name.underscore.pluralize.to_sym
6061
end
61-
@foreign_key =
62+
@foreign_key = options.fetch(:foreign_key) do
6263
if collection?
6364
"#{name.to_s.singularize}_ids".to_sym
6465
else
6566
"#{name}_id".to_sym
6667
end
68+
end
6769
end
6870

6971
# @api public

0 commit comments

Comments
 (0)