Jez Caudle
Jez Caudle

Reputation: 115

Rails order not working with only

I can't find this documented anywhere but here is my problem: when I query via active record and use "only" the "order" clause is ignored. For example I have a Blog model:

Blog.order('id desc')

returns all the blogs with the highest ID first - as expected but:

Blog.order('id desc').only(:id)

returns only the id's (as expected) but the order clause is completely ignored, the smallest id comes first.

I have tested this with Ruby 1.9.3p327 and both Rails 4.0.0.beta1 and Rails 3.2.13 and I get the same results.

Is this a feature or a bug? To me it's a bug because the Rails crew were trumpeting how find_by_sql is not really needed but in this case it is:

Blog.find_by_sql("select id from blogs order by id desc")

which gives the correct answer.

Upvotes: 1

Views: 1434

Answers (1)

PinnyM
PinnyM

Reputation: 35541

Try using pluck instead of only. only is used to override portions of the previously formed query chain. As the the docs demonstrate:

Post.where('id > 10').limit(20).order('id desc').only(:order, :where)

results in:

SELECT * FROM posts WHERE id > 10 ORDER BY id DESC

This is because the limit modification will be ignored, since the list passed to only doesn't include :limit.

UPDATE

If you need an actual model object returned instead of an array of id's, use select:

Blog.order('id desc').select('id')

Upvotes: 1

Related Questions