9

コールバックを使用できることはわかっていますが、これは実現可能です。私は長い間検索を行いましたが、結果はありませんでした。これは私がうまくいくと思ったものです。

def User < ActiveRecord::Base
  has_many :documents
  has_many :draft_docs     , :class_name => 'Document', :conditions => { :status => 'draft' }
  has_many :published_docs , :class_name => 'Document', :conditions => { :status => 'published' }
  has_many :private_docs   , :class_name => 'Document', :conditions => { :status => 'private' }
end

def Document < ActiveRecord::Base
  belongs_to :user      , :counter_cache => true
  belongs_to :user      , :inverse_of => :draft_docs    , :counter_cache => true
  belongs_to :user      , :inverse_of => :published_docs, :counter_cache => true
  belongs_to :user      , :inverse_of => :private_docs  , :counter_cache => true
end

published_docs_count ではなく、documents_count を更新しているため、計画どおりに機能していません。

ruby-1.9.2-p180 :021 > User.reset_counters 2, :published_docs  User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1
   (0.7ms)  SELECT COUNT(*) FROM `documents` WHERE `documents`.`user_id` = 2 AND `documents`.`status` = 'published'
   (2.2ms)  UPDATE `users` SET `documents_count` = 233 WHERE `users`.`id` = 2
 => true
4

2 に答える 2

2

これは、すべての関連付けに同じ名前を使用しているためです。

belongs_to :user, :counter_cache => true
belongs_to :user_doc, :class_name => "User", 
           :inverse_of => :draft_docs, :counter_cache => :draft_docs_count

この機能は、コールバックを追加してカウントをインクリメントすることによって実装されます。あなたの場合、document.userすべてに同じ名前を使用したため、ターゲットは です。

于 2012-07-22T01:32:06.853 に答える
1

counter_culture gemを使用します。

  • テーブルに 3 つの列を追加しusersます。

    add_column :users, :draft_documents_count, :integer, null: false, default: 0
    add_column :users, :published_documents_count, :integer, null: false, default: 0
    add_column :users, :private_documents_count, :integer, null: false, default: 0
    
  • Documentモデルを装飾する

    class Document
      counter_culture :user, :column_name => Proc.new do |doc|
        if %w(draft published private).include?(doc.status) 
          "{doc.status}_documents_count"
        end
      end    
    end
    
  • コンソールでコマンドを実行して、現在の行のカウントをシードします

    Document.counter_culture_fix_counts
    

古い答え

オプションにカウンター列名 (を除くtrue) をcounter_cache指定できます。

class Document < ActiveRecord::Base
  belongs_to :user, :counter_cache => true
  belongs_to :user, :inverse_of => :draft_docs, 
                                   :counter_cache => :draft_docs_count
  belongs_to :user, :inverse_of => :published_docs, 
                                   :counter_cache => :published_docs_count
  belongs_to :user, :inverse_of => :private_docs, 
                                   :counter_cache => :private_docs_count
end
于 2011-09-18T04:30:06.457 に答える