Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active Record undefined method read_attribute_for_serialization

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.

like image 639
Lucho Tc Avatar asked Oct 18 '22 02:10

Lucho Tc


1 Answers

either a single object or an empty Active Record Relation

I think this is the issue. I think you should either

  • always return a collection. a collection of a single object or empty collection
  • either return a single object or nil

With the first option, you could always use each_serializer. With the second option, you could always use serializer.

like image 200
kcdragon Avatar answered Oct 21 '22 00:10

kcdragon