使用'counter_cache'与'primary_key'不同于'id'的麻烦

时间:2012-02-28 04:50:24

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

我正在使用Ruby on Rails 3.1,我希望counter_cache belongs_toprimary_key的{​​{1}}关联,共同的id密钥并正确运行相关的迁移以添加计数器功能。

也就是说,我有这些课程:

class User < ActiveRecord::Base
  belongs_to :authorization,
    :class_name    => 'Authorization',
    :foreign_key   => 'authorization_name',
    :counter_cache => :users_count
end

class Authorization < ActiveRecord::Base
  self.primary_key = "name"

  has_many :users,
    :class_name  => 'User',
    :primary_key => "name",
    :foreign_key => "authorization_name"
end

在我的迁移文件中,我有:

add_column :authorizations, :users_count, :integer, :default => 0

User.reset_column_information
User.find_each do |user|

  # By using the following code I get a "undefined method `counter_cache_column'
  # for nil:NilClass" error
  User.reset_counters(user.id, :authorization)

  # I also tried the following code but it still doesn't work.
  #
  #   User.reset_counters(user.users_authorization_system_name, :authorization)
  #
  # I get a "Couldn't find User with id=default" error when migrating.
  #
end

怎么了?是否可以向我的班级添加counter_cache功能?如果是这样,我该如何做到?

1 个答案:

答案 0 :(得分:0)

在我看来,问题是你是否正确更改了主键?

Using Rails, how can I set my primary key to not be an integer-typed column?