The reason of confusion is a CollectionProxy in ActiveRecord::Associations
(things are bit more complicated, than they looked):
current_user.accounts
is a CollectionProxy, not an Array
.
Think of CollectionProxy as of container, which internally has @owner
as current_user, @target
as set of accounts and @reflection
- kinda links (associations) between @owner
and @target
When you run current_user.accounts.new()
- you just add another object into @target
, so iterating over current_user.accounts
you're iterating over @target, which contains objects including newly created.
But wait, why does .count
return less objects?
Because Rails are lazy and @target
is not loaded until you really need its objects(=accounts). So to just run .count
it's cheaper to run direct SQL-request instead of instantiation of all objects in @target
and then count 'em.
That's why when you do current_user.accounts.count
you get amount of saved objects. And when you do current_user.accounts.all.count
- it instantiate all objects in @target
, convert 'em into Array
and count accounts in this array (equal to current_user.accounts.size
).
BTW, all
is deprecated in Rails 4, use to_a
instead
So, what do I do with all this knowledge, man? I just need to show accounts without unsaved one.
Just force reload: @accounts = current_user.accounts(force_reload = true)
OR @accounts = current_user.accounts.reload
OR @accounts = current_user.accounts.order('created_at DESC')
It will run reload automagically because order needs direct request to objects via SQL