On Wed, May 27, 2009 at 3:08 AM, Julian Leviston <[email protected]>wrote:
>
>
> On 27/05/2009, at 7:32 PM, Vipin wrote:
>
> >
> >
> >>> so basically, I must use
> >>> <% if @forms.count != 0 %>
> >>
> >> @forms.any? is slightly more idiomatic ruby
> >
> > <% if @forms.any? %>
> > is working and i believe it doesn't have the penalty of SQL query
> > too.
> >
>
> @forms.count won't work because @forms will most likely be an Array
> object, and an Array doesn't respond to count... it'll respond to
> size, tho...
An Array instance can respond to both count and size methods. If you use
size the method with a counter
cache column on the has_many side, you can cache the total. For example,
you can do something
like this
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post, :counter_cache => true
end
Note: You would add the counter cache column on the posts table like this
using a migration:
add_column :posts, :comments_count, :integer, :default => 0
Good luck,
-Conrad
>
> @forms.size != 0
>
> or you could do this
>
> unless(@forms.blank?)
>
> None of these will do a db connection because @forms contains objects
> which have already been loaded (if they're from the database).
>
> Julian.
>
> ----------------------------------------------
> Learn: http://sensei.zenunit.com/
> Last updated 20-May-09 (Rails, Basic Unix)
> Blog: http://random8.zenunit.com/
> Twitter: http://twitter.com/random8r
>
>
> > thanks
> > vipin
> >
> >
> > >
>
>
> >
>
--~--~---------~--~----~------------~-------~--~----~
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 [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---