Je découvre avec émerveillement l’attribut :include d’ActiveRecord::Base, qui efface de mon esprit des années de cauchemars SQL.

Jugez plutôt, quand une horreur pareille

self.find_by_sql([%{
  SELECT categories.id, categories.name, categories.permalink, categories.position, 
    COUNT(articles.id) AS article_counter
  FROM #{Category.table_name} categories
  LEFT OUTER JOIN #{Category.table_name_prefix}categorizations#{Category.table_name_suffix} articles_categories
    ON articles_categories.category_id = categories.id
  LEFT OUTER JOIN #{Article.table_name} articles
    ON (articles_categories.article_id = articles.id AND articles.published = ?)
  GROUP BY categories.id, categories.name, categories.position, categories.permalink
  ORDER BY position
}, true]).each {|item| item.article_counter = item.article_counter.to_i }

devient tout simplement :

self.find(
  :all, 
  :include => :articles, 
  :conditions => ['contents.published = ?', true], 
  :order => 'position').each { |cat| cat.update_attributes(:article_counter => cat.articles.length) }

C’est beau, pour un peu j’en pleurerais.

Le long de la Seine

Perry the Platypus wants you to subscribe now! Even if you don't visit my site on a regular basis, you can get the latest posts delivered to you for free via Email: