Rails 3: Empty ActiveRecord Object on Output

I’ve tried to debug a weird Rails issue I’ve had with no luck.

The Situation

When I output a nested relationship object with to_json , I have one association where Rails will output a blank object instead of just an empty array. However, if I output the same thing in the Rails console, it’s an empty array.

For example: I have a job object, which can have many changes associated with it. So, in a shortened version of my code I have this:

window.job = <% @job.to_json( :include => {
    :changes => {
        :include => [:user]
} ).html_safe %>

The Result

What this will do is output my Job JSON object, but instead of job.changes >> [], it will be: job.changes >> [{attr_1: null, attr_2: null, attr_3: null}]. Even if I just try to say <%= @job.changes %> it will output:

[#<Change id: nil, job_id: 47, description: "", completed: false, round: nil, completed_by: nil, user_id: nil, created_at: nil, updated_at: nil>]

What’s even more confusing is that even when there are changes, Rails will output an array of those changes with an empty change object in the array.

The weirder part is when I try to duplicate it in the Rails Console, it doesn’t happen:

$ > @job = Job.find(47)
  Job Load (0.5ms)  SELECT `jobs`.* FROM `jobs` WHERE `jobs`.`id` = 47 ORDER BY jobs.created_at DESC LIMIT 1
 => #
$ > @job.changes
Creating scope :page. Overwriting existing method Change.page.
  Change Load (0.3ms)  SELECT `changes`.* FROM `changes` WHERE `changes`.`job_id` = 47 ORDER BY changes.created_at ASC
 => []
$ > @job.changes
 => "[]"

I’m not sure if I’m doing something wrong or if this is a bug in Rails 3.1.3. It doesn’t seem to happen with any of my other associations. Has anyone else run across this at all?

Tagged: ,

2 Responses to Rails 3: Empty ActiveRecord Object on Output

  1. J B says:

    I am currently stuck on this same bug. Did you ever find a solution?

    • Tony Stuck says:

      Unfortunately not.. I was hoping someone would come across this post and know what the problem is. My solution at the time of writing was to filter out the empty record when processing the JSON object. Very hacky, but the project had to get done :-/

Leave a Reply

Your email address will not be published. Required fields are marked *