gpt4 book ai didi

ruby-on-rails - 带条件的counter_cache

转载 作者:行者123 更新时间:2023-12-04 04:31:58 39 4
gpt4 key购买 nike

我知道我可以使用回调,但这应该是可行的。我做了很长时间的搜索,没有结果。我认为这是行得通的。

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

如您所见,它的更新documents_count而不是published_docs_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

最佳答案

使用counter_culture gem。

  • 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

    关于ruby-on-rails - 带条件的counter_cache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7459275/

    39 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com