Issue with has_many and Array.empty?

I've posted a narrative of my issue on the Google Rails Group:


/app/controllers/document_groups_controller.rb
def show
@document_group = DocumentGroup.find(params[:id])
@journal = Journal.find(params[:journal_id])
@document_group_templates = @document_group.document_templates
@logger = RAILS_DEFAULT_LOGGER

#
# this is the money line: comment it out and @document_group_templates.empty?
# is true in the view. leave it in, and it's false. true is correct.
#
@logger.debug "###### --->" + @document_group_templates.inspect
#
# it turns out that this triggers the SQL to be run by Rails that acutally
# populates the @document_group_templates Array.
#

render :action => :show, :layout => 'ajax_div'
end


/app/views/document_groups/show.rhtml
#
#@document_group_templates.empty? evaluates to true without the inspection above
#
<% if !@document_group_templates.empty? %>
#
# now, what's interesting is that if i change this to
#
# if @document_group_templates.count > 0
#
# that also triggers the SQL to be run. but, interestingly, #size does not
# trigger the SQL.
#
<ul>
<%
@document_group_templates.each do |child|
%><li><%= link_to child.name, :controller => :template, :action => :show, :id => child.id %><%
end
%>
</ul>
<% end %>

/app/models/document_group.rb
class DocumentGroup < ActiveRecord::Base
has_many :document_templates, :order => :document_group_position
acts_as_tree :counter_cache => true
end

/app/models/document_template.rb
class DocumentTemplate < ActiveRecord::Base
belongs_to :document_group, :counter_cache => true
acts_as_list :scope => :document_group, :column => :document_group_position
end

No comments: