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?