Rails 4: undefined method `primary_key_name'

2019-06-26 01:20发布

I'm receiving the following error using Rails 4.0.0.beta:

NoMethodError: undefined method `primary_key_name' for #<ActiveRecord::Reflection::AssociationReflection

I don't get the exception when using Rails 3.2.x.

I'm using Ruby 1.9.3-p194 for both Rails 3.2.13 and Rails 4.0.0.beta.

The problem stems from the following has_many statement:

class Store < ActiveRecord::Base
  has_many :relationships
  has_many :customers, :through => :relationships, :source => :user,
    :conditions => { :relationships => { :description => "Customer" } } do
      def <<(user)
        proxy_association.owner.relationships.create(:description => "Customer", :user => user)
      end
    end
end

I have following supporting classes:

class User < ActiveRecord::Base
  has_one :relationship
  has_one :store, :through => :relationship
end

class Relationship < ActiveRecord::Base
  belongs_to :store
  belongs_to :user
end

I'd like to know how I can achieve the same has_many functionality using a Rails 4-friendly code?

P.S. I'm aware I'm still using old-style syntax, and that the conditions hash now requires a proc or lambda, but these shouldn't causing the undefined method exception.

1条回答
欢心
2楼-- · 2019-06-26 01:23

I found the culprit, it's the perfectline/validates_existence gem which defaults to the deprecated primary_key_name instead of foreign_key when the ActiveRecord::VERSION::MINOR >= 1 - go figure! I've submitted a pull request with the fix (https://github.com/perfectline/validates_existence/pull/20). Thanks for pointing me in the right direction @Beerlington.

查看更多
登录 后发表回答