Question

So here's a fun one — I have a controller method that returns a list of "resumable" objects based on some rules. But, there are criteria i can't include in a single database query — so, I'd like to render out the "base" resumable list, and then essentially run a filter on it prior to returning to the client.

In other words, what I'm trying to do is:

sessions = ended_sessions.where("current_date <= (created_at + interval '12 hours')")

json = JSON.parse(SessionResumeSerializer.new(sessions).as_json)

json.each do |session|
 # additional processing
end

Anyway, SessionResumeSerializer.new(sessions).as_json totally doesn't work, throwing an :

NoMethodError: undefined method 'read_attribute_for_serialization' for <ActiveRecord::Relation:0x007ffa164b0ce0> error.

I'm clearly confused about how this is supposed to work — seems completely intuitive that the initializer would take a relation and render it out.

Is there a better way to go about this?

Was it helpful?

Solution

The issue here is that your "sessions" variable refers to an array and not a session object. What you are doing would have worked perfectly for a single session (of class SessionResume) but for an array you need to do something like the following:

sessions = ended_sessions.where("current_date <= (created_at + interval '12 hours')")
json     = JSON.parse(ActiveModel::ArraySerializer.new(sessions).as_json)

json.each do |session|
    # additional processing
end

Note that you need to use ActiveModel::ArraySerializer rather than the class specific, single-object serializer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top