Reputation: 81
having a problem with sending parameters. I have user_serializer and book_serializer and I want to send user_id to book_serializer inside user_serializer. Like this:
class UserSerializer < ActiveModel::Serializer
attributes :id
has_many :books, serializer: BookSerializer, your_option_name: object.id
end
and then BookSerializer
class BookSerializer < ActiveModel::Serializer
attributes :id, :test
def test
@instance_options[:your_option_name]
end
end
but it's not working, getting null.
are there any ideas? great thanks.
Upvotes: 0
Views: 1647
Reputation: 841
The arguments that you passed into has_many ...
is actually used to create a HasManyReflection object which only accepts some very specific values and it also does not pass its argument any further.
The correct way to pass custom argument to nested serializers is through the build_association method or directly like below:
class UserSerializer < ActiveModel::Serializer
attributes :id, books
def books
ActiveModel::SerializableResource.new(object.books, each_serializer: BookSerializer, your_option_name: object.id)
end
end
Upvotes: 1