1

Background Information:
Models: App and Announcement
Associations: app has_many announcements

Situation: I have a very simple index action in my AnnouncementsController

def index
  app = App.find(params[:app_id])
  @announcements = app.announcements
end

I was using the jbuilder gem to output json and it indicated that my @announcements array is empty, but I'm sure I have records in it. I checked the source and noticed that it used the 'empty?' method to check if the collection is empty before it proceeds. I wanted to see what the 'empty?' method returns so I added a line to the index action:

def index
  app = App.find(params[:app_id])
  @announcements = app.announcements
  puts @announcements.empty?.to_s # Returns: "true"
end

"True" was not I was expecting because I'm sure I have data. So I added an 'inspect' call to check the contents in the @announcement variable:

def index
  app = App.find(params[:app_id])
  @announcements = app.announcements
  puts @announcements.inspect # Returns: "[#<Announcement id: 1, app_id: 1, title: \"20% off everything!\", content: \"Enjoy 20% off everything from now until yesterday!!...\", image: \"0e06b94d-1ac6-4d90-b937-9fa7bfaf90c9.jpg\", status: 0, created_at: \"2012-08-27 15:33:00\", updated_at: \"2012-08-27 15:33:00\">]"
  puts @announcements.empty?.to_s # Returns: "false"
end

Hm... interesting. So without changing anything except adding an 'inspect' to my variable, the 'empty?' method returned a different result.

Another interesting observation I made is that if i did this instead:

def index
  @announcements = Announcement.all
  puts @announcements.empty?.to_s # Returns: "false"
end

The 'empty?' worked fine.

Is anyone else having the same problem, or is it just me?

mu is too short
  • 426,620
  • 70
  • 833
  • 800
mountriv99
  • 923
  • 8
  • 13

1 Answers1

0

Rails load collections in a lazy way, so when you inspect it loads it is not empty anymore.

Migore
  • 1,477
  • 3
  • 19
  • 40
  • Hm.. i see... but I don't wanna put a meaningless inspect there, what would be the proper way to do this? – mountriv99 Aug 28 '12 at 05:04
  • Try `@announcements = app.announcements.all`. – Gabe Kopley Aug 28 '12 at 06:02
  • You cab do a include in the find if you just want to change this query or set the default on the model. Check this questions for more info on how to do this: http://stackoverflow.com/questions/2042507/rails-eager-loading-on-all-finds – Migore Aug 28 '12 at 13:44