Thursday, May 27, 2010

[Rails] Re: collection.last does not seem to jive with collection.count after collection.build

Thanks, Jeff.

Thanks for the clarification of the difference between .size
and .count. I was actually looking more for something that does .last
like .count, rather than .count like .last. I got around that by doing
and :order_by => 'created_at' before using .last, which puts the nils
at the head, at least in MySQL and SQLite.

Big thanks for clone. It's brilliant. I didn't know it existed. It was
beginning to look like a maintenance nightmare without it.

On May 27, 3:09 pm, Jeff <cohen.j...@gmail.com> wrote:
> On May 27, 11:47 am, Dee <dger...@gmail.com> wrote:
>
> > I was just trying to write a "smart" copy method in a class* and
> > noticed that the last and count collection methods don't work the same
> > after build and before save. In other words, if in my code I do this:
>
> >     user = User.new
> >     user.save
> >     purchase = user.purchases.build
>
> > Then I get the following:
> >     user.purchases.count => 0
> >     user.purchases.last => #<Purchase:0x01234567>
>
> That's because .count is using SQL to look at the table, but you
> haven't committed the new purchase to the db yet.  .last knows to use
> the in-memory collection instead.
>
> Instead of .count, use .size, which is aware of in-memory changes.
>
> That said, consider using .clone, which will copy an object for you
> that you can start with.
>
> Jeff
> purpleworkshops.com

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate