【问题标题】:Trouble on using 'counter_cache' with a 'primary_key' different from 'id'使用与“id”不同的“primary_key”使用“counter_cache”时出现问题
【发布时间】:2012-02-28 04:50:24
【问题描述】:

我正在使用 Ruby on Rails 3.1,我想将 counter_cache belongs_to 与 primary_key 关联,不是常见的 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 功能添加到我的班级?如果是这样,我该怎么做?

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-23
      • 2018-12-06
      • 2010-12-27
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多