Hi, this blog is no longer maintained, my new blog is here

Ruby On Rails and a Conning Israeli entrepreneur

counter_cache

Many times when using a belongs_to relation, we encounter the need to size up that association, we can use 2 methods which are created for us, size and (association_pluralization)_count.

so if SuperHero has_many :super_powers than:


me = SuperHero.find(1)
me.super_powers.size
me.super_powers_count


they will both issue that same SQL statement at this point


SELECT count(*) as count_all FROM super_powers WHERE (super_hero_id = 1)

which basically preforms a SELECT * statement, we don't like it :)

the :counter_cache parameter for the belongs_to macro, indicates the use of a
(association_pluralization)_count named column which will be incremented and decremented according to the use of the associative array, this can and does save a lot of time and DB - APP - DB roundup's.



0 comments:


The Web Ask eizesus.com

Subscribe

    follow me on Twitter

    Twiters Around

    About Me

    My photo
    I am a web developer for more than 9 years, managed, cried, coded, designed and made money in this industry. now trying to do it again.

    Labels