Skip to content

Commit af81a40

Browse files
committed
Passes serializer options down into associations
1 parent bcd3844 commit af81a40

File tree

3 files changed

+18
-5
lines changed

3 files changed

+18
-5
lines changed

lib/active_model/serializer.rb

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -176,19 +176,20 @@ def attributes(options = {})
176176
end
177177

178178
def each_association(&block)
179-
self.class._associations.dup.each do |name, options|
179+
self.class._associations.dup.each do |name, association_options|
180180
next unless object
181181

182182
association = object.send(name)
183183
association_value = send(name)
184-
serializer_class = ActiveModel::Serializer.serializer_for(association, options)
184+
serializer_class = ActiveModel::Serializer.serializer_for(association, association_options)
185+
185186
serializer = serializer_class.new(
186187
association_value,
187-
serializer_from_options(options)
188+
serializer_from_options(association_options).merge(options)
188189
) if serializer_class
189190

190191
if block_given?
191-
block.call(name, serializer, options[:association_options])
192+
block.call(name, serializer, association_options[:association_options])
192193
end
193194
end
194195
end

test/fixtures/poro.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,10 @@ def self.root_name
9999

100100
belongs_to :post
101101
belongs_to :author
102+
103+
def custom_options
104+
options
105+
end
102106
end
103107

104108
AuthorSerializer = Class.new(ActiveModel::Serializer) do

test/serializers/associations_test.rb

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def setup
3737
@post.author = @author
3838
@author.posts = [@post]
3939

40-
@post_serializer = PostSerializer.new(@post)
40+
@post_serializer = PostSerializer.new(@post, {custom_options: true})
4141
@author_serializer = AuthorSerializer.new(@author)
4242
@comment_serializer = CommentSerializer.new(@comment)
4343
end
@@ -65,6 +65,14 @@ def test_has_many_and_has_one
6565
end
6666
end
6767

68+
def test_serializer_options_are_passed_into_associations_serializers
69+
@post_serializer.each_association do |name, association|
70+
if name == :comments
71+
assert association.first.custom_options[:custom_options]
72+
end
73+
end
74+
end
75+
6876
def test_belongs_to
6977
assert_equal(
7078
{ post: { type: :belongs_to, association_options: {} },

0 commit comments

Comments
 (0)