Rails 4: undefined method `primary_key_name'

白昼怎懂夜的黑 提交于 2019-12-10 16:35:35

问题


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:


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.



来源:https://stackoverflow.com/questions/15360418/rails-4-undefined-method-primary-key-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!