I have a rails scope that gets the first record of a table and assings it to a @variable. It returns either a single object or an empty Active Record Relation. My problem is that i'm using a custom serializer to render the json but if the scope returns an empty Active Record Relation I get the "Active Record undefined method read_attribute_for_serialization" unless i use each_serializer, but if the the scope returns an object i have to render it using serializer: Is there any way of solving this without doing this :
if @variable.blank?
render json: @variable, each_serializer: CustomSerializer
else
render json: @variable, serializer: CustomSerializer
end
Update
I have to get the latest record from the Products table. So i have defined a scope like this:
scope :last_by_period, -> { order('period desc').first }
So this scope returns an empty Active Record Relation if there are no Products records in my db.
either a single object or an empty Active Record Relation
I think this is the issue. I think you should either
With the first option, you could always use each_serializer
. With the second option, you could always use serializer
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With