reset_counters rails undefined方法错误,但在类似的关系上工作正常

时间:2014-05-11 19:34:20

标签: ruby-on-rails ruby-on-rails-3

我尝试将 counter_cache 添加到用户以计算所拥有的项目

用户有很多项目,Project有很多用户,但Project属于其中一个。

所以我编写了一个用于为counter_cache添加额外计数字段的迁移。

评论reset_counter没有问题。

User.reset_counters user.id, :projects引发 NoMethodError:未定义的方法`counter_cache_column'为零:NilClass

项目上的counter_cache也正常运行。如果我添加额外的项目,它将增加projects_count字段,如果我删除一个 - 减量。

模型

class User < ActiveRecord::Base
  has_many :projects, :through => :team_members
  has_many :team_members

class TeamMember < ActiveRecord::Base
  belongs_to :user
  belongs_to :project

class Project < ActiveRecord::Base
  has_many :users, :through => :team_members
  has_many :team_members
  belongs_to :leader, :class_name => :User, :counter_cache => true

class Comment < ActiveRecord::Base
  belongs_to :user, :counter_cache => true

移植

class AddCounters < ActiveRecord::Migration
  def up
    add_column :users, :comments_count, :integer, :default => 0
    add_column :users, :projects_count, :integer, :default => 0 

    User.reset_column_information

    User.find_each do |user| 
      User.reset_counters user.id, :comments #all fine

      User.reset_counters user.id, :projects #raise NoMethodError
                                             #undefined method `counter_cache_column'
                                             #for nil:NilClass
    end
  end

  def down
    remove_column :users, :projects_count
    remove_column :users, :comments_count
  end
end

我尝试从:counter_cache => true切换到:counter_cache => :projects_count

同样的事情。

1 个答案:

答案 0 :(得分:4)

您是否应该告诉模特他们有:team_members:through次来电?尝试添加:

has_many :team_members

同时使用UserProject模型。


编辑:仔细查看您的设置,问题似乎是您在:leader关系上设置了计数器缓存,该关联没有相应的反转User方面。我不确定你想要它的方式,但这是我如何描绘选项:

选项1:为用户提供单独的:lead_projects关联

class User < ActiveRecord::Base
  has_many :lead_projects, :class_name => :Project, :inverse_of => :leader

class Project < ActiveRecord::Base
  belongs_to :leader, :class_name => :User, :counter_cache => :lead_projects_count, :inverse_of => :lead_projects

以及将:lead_projects_count添加到:users表的迁移。

选项2:让:projects_count计数器通过TeamMembers

根据this similar answer

class User < ActiveRecord::Base
  has_many :team_members
  has_many :projects, :through => :team_members

class TeamMember < ActiveRecord::Base
  belongs_to :user, :counter_cache => :projects_count
  belongs_to :project

class Project < ActiveRecord::Base
  has_many :team_members
  has_many :users, :through => :team_members

使用此选项,我认为您当前的迁移已足够。


注意:我只是在我去这里时编写代码;如果我的语法错误,请发表评论,以便为未来的读者编辑我的答案。