Surprising behavior of ActiveRecord order method

11 views
Skip to first unread message

Doug Orleans

unread,
May 6, 2013, 3:55:38 PM5/6/13
to boston-r...@googlegroups.com
This behavior surprised me, but I can't decide if it's a bug or not:

Loading development environment (Rails 4.0.0.rc1)
2.0.0p0 :001 > p = Post.new
=> #<Post id: nil, title: nil, text: nil, created_at: nil, updated_at: nil>
2.0.0p0 :002 > p.comments.build
=> #<Comment id: nil, commenter: nil, body: nil, post_id: nil, created_at: nil, updated_at: nil>
2.0.0p0 :003 > p.comments.size
=> 1
2.0.0p0 :004 > p.comments.order(:created_at).size
=> 0

What do you think?

--Doug

rtwomey

unread,
May 6, 2013, 4:01:40 PM5/6/13
to boston-r...@googlegroups.com
Hi Doug,

Build doesn't save the comment. The order method is doing a lookup in the db and ordering by whatever criteria you specify. Since there's nothing actually saved, it won't return anything.

Try switching build to create (and passing in whatever params you need), then running it again. The order line should return results.
-Ryan

--
You received this message because you are subscribed to the Google Groups "Boston Ruby Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to boston-rubygro...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Doug Orleans

unread,
May 6, 2013, 4:12:27 PM5/6/13
to boston-r...@googlegroups.com
I understand that it only includes persisted objects, but other AR methods (e.g. size) seem to do the right thing and include both persisted and non-persisted. I'm wondering if it's a bug that order doesn't do the right thing here too, or if there should be another method to do what I want it to do.

--Doug

Brice Stacey

unread,
May 6, 2013, 4:50:51 PM5/6/13
to boston-r...@googlegroups.com
When you call `order(:created_at)` you're actually creating a new AR Relation and since it hasn't been executed yet it will hit the database. If you want an in memory sort use `sort_by` or be sure to only use a single relation (e.g. don't call p.comments and later p.comments(:created_at). Instead, save `comments = p.comments.order(:created_at)` and use `comments`).
Reply all
Reply to author
Forward
0 new messages