Whilst working on client projects we often find useful bits of information out. Where possible we blog about that information to pass on our knowledge. Below are some of our most recent entries.
inherited_resources and mongo_mapper gotcha in Rails 2
Having just started using inherited_resources and mongo_mapper we found a strange problem occurring in our tests.
We are currently working on our first commercial project and we decided to use a few new gems in the project that we hadn't used before. Two of those gems were inherited_resources and mongo_mapper. We soon found a problem occurring in all of our object listing pages.
You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.length (ActionView::TemplateError) On line #1 of app/views/admin/shared/_index.html.erb 1: <% if collection.length > 0 -%> 2: <ul> 3: <% collection.each do |object| -%> 4: <li>
After a little digging around we found that there was a conflict in how the 1.0 branch of inherited_resources created the collection object (We are using the 1.0 branch as the 1.1 branch is for Rails 3 and not backwards compatible). The offending code is in the InheritedResources::BaseHelpers module.
def collection get_collection_ivar || set_collection_ivar(end_of_association_chain.find(:all)) end
Mongo_mapper doesn't understand the call to .find(:all), but uses the ActiveRecord 3 convention of .all, so we updated the code in the BaseHelpers module to reflect this.
def collection get_collection_ivar || set_collection_ivar(end_of_association_chain.all) end
Hopefully this helps others avoid this confusion.Tweet