Rails 7.1: ActiveModel::Serializer not serializing nested associations correctly when using conditional attributes
I'm trying to figure out I'm encountering an issue with ActiveModel::Serializers in my Rails 7.1 application where nested associations are not being serialized correctly when applying conditional attributes. I'm trying to serialize a `Post` model that has many `Comments`, and I want to include the `user` information for each comment only if the `user` is not nil. Here's the serializer I wrote: ```ruby class PostSerializer < ActiveModel::Serializer attributes :id, :title, :body, :comments def comments ActiveModelSerializers::SerializableResource.new(object.comments, each_serializer: CommentSerializer) end end class CommentSerializer < ActiveModel::Serializer attributes :id, :content attribute :user, if: -> { object.user.present? } # This line seems to be causing the issue end ``` When I call `render json: @post, serializer: PostSerializer`, I expect each comment to either include or exclude the `user` attribute based on whether it exists. However, I am still seeing `user` as `null` in the JSON response when the user is nil, rather than omitting the attribute completely. I have also tried using `ActiveModel::Serializer::Performance::SerializableResource` and looked into using `serializer_options`, but the issue persists. Additionally, I verified that the `user` associations are correctly set on the comments, and I can see them in the console. Hereβs the JSON output Iβm getting, which includes `user: null`: ```json { "post": { "id": 1, "title": "Sample Post", "body": "This is an example.", "comments": [ { "id": 1, "content": "Great post!", "user": null }, { "id": 2, "content": "Thanks for sharing!", "user": { "id": 1, "name": "John Doe" } } ] } } ``` Is there a way to ensure that the `user` attribute is completely omitted from the serialized output when it is nil? Any insights or workarounds would be greatly appreciated! I've been using Ruby for about a year now. Could this be a known issue? I recently upgraded to Ruby latest. Any examples would be super helpful.