Rails: find_by_sql and virtual column

前端 未结 2 571
有刺的猬
有刺的猬 2020-12-29 09:51

I want to display a list with tags plus the number of elements (in my example \"Tasks\") for each tag.

For this purpose I created the following method in my Tag mode

2条回答
  •  灰色年华
    2020-12-29 10:05

    The "Rails way" is to use a counter_cache:

    class Tag < ActiveRecord::Base
      has_many :tag_tasks
      has_many :tasks, :through => :tag_tasks
    end
    
    # the join model
    class TagTask < ActiveRecord::Base
      belongs_to :tag, :counter_cache => true
      belongs_to :task
    end
    
    class Task < ActiveRecord::Base
      has_many :tag_tasks
      has_many :tags, :through => :tag_tasks
    end
    

    This requires adding a tag_tasks_count column on your 'Tag' table.

    If you add a named_scope to Tag like so:

    class Tag ...
      named_scope :active, lambda { { :conditions => { 'deleted' => 0, 'finished' => 0 } } }
    end
    

    Then you can replace all Tag.find_by_count with Tag.active. Use it like this:

    Tag.active.each do |t|
      puts "#{t.name} (#{t.tag_tasks_count})"
    end
    

提交回复
热议问题