Monday, October 22, 2012

Another reason to be careful when using default_scope

I had the following in a model:

default_scope order(:name)

tried doing a distinct:

MyModel.select("distinct my_attribute").map(&:my_attribute)

and got:

MyModel problem: PG::Error: ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ...CT distinct record_status FROM "my_models"  ORDER BY name
                                                                   ^
: SELECT distinct my_attribute FROM "my_models"  ORDER BY name

This looks like a great reason not to use default_scope with an order.

As Dave Thomas mentioned in another related post on the subject, you can use:

MyModel.unscoped.select("distinct my_attribute").map(&:my_attribute)

But, like Dave said, that seems like an accident waiting to happen.

No comments: