Tuesday, March 25, 2014

Model is a poor scope name in Ruby on Rails 4

Upgrading from Rails 3.2 to Rails 4.0 is not a trivial task. Sure, there is a guide, but when you upgrade you'll probably be upgrading a lot of your gems, maybe your jQuery and jQuery-UI versions and then there are all the undocumented unintentional changes that can cause you grief. If you've got a good test suite (you have one right?) you'll catch a lot of these, but some will leave you scratching your head. This one tripped me up for a while: we had a very simple scope stop working in Rails 4.

The scope model below works in Rails 3.2, but fails in Rails 4 when used with an association:

Here is the failure:

In the second query, post.comments.model.count the query has lost the comments scope as well as the conditional defined in our model scope and it counts all comments in the system.

The fix is quite easy, just change the name of the scope to something like not_index.

This seems to be change in associations that is most clearly illustrated by this:

I could never quite figure out where in activerecord this changed, but model was not a great choice for a scope name. This executable gist has everything in this post if you want to explore this more.

What surprises have you found with Rails 4?

No comments:

Post a Comment