1

I am using Ruby on Rails 3.1 and I would like to counter_cache a belongs_to association with a primary_key that is not the common id key and to properly run related migrations in order to add counter functionalities.

That is, I have these classes:

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

In my migration file I have:

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

What's wrong? Is it possible to add counter_cache functionalities to the my class? If so, how can I make that?

Backo
  • 18,291
  • 27
  • 103
  • 170

1 Answers1

0

It seems to me, the problem is whether correctly have you changed the primary key?

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

Community
  • 1
  • 1
Valery Kvon
  • 4,438
  • 1
  • 20
  • 15