Rails 4.1.x HABTM未定义方法'foreign_key'

时间:2014-07-07 18:48:11

标签: ruby-on-rails ruby-on-rails-4.1

以下定义适用于Rails 4.0.x及更低版本:

module Gemgento
   class Product < ActiveRecord::Base
      has_and_belongs_to_many :stores, -> { distinct }, join_table: 'gemgento_stores_products', class_name: Gemgento::Store
   end
end

但是,升级到Rails 4.1.x后,每当Gemgento::Product类初始化时,我都会收到以下错误。

NoMethodError: undefined method `foreign_key' for #<Class:0x007f870f18e668>
from /Users/Kevin/.rvm/gems/ruby-1.9.3-p429@sellect/gems/activerecord-4.1.4/lib/active_record/dynamic_matchers.rb:26:in `method_missing'
from /Users/Kevin/.rvm/gems/ruby-1.9.3-p429@sellect/gems/activerecord-4.1.4/lib/active_record/associations/builder/has_and_belongs_to_many.rb:113:in `belongs_to_options'
from /Users/Kevin/.rvm/gems/ruby-1.9.3-p429@sellect/gems/activerecord-4.1.4/lib/active_record/associations/builder/has_and_belongs_to_many.rb:82:in `through_model'
from /Users/Kevin/.rvm/gems/ruby-1.9.3-p429@sellect/gems/activerecord-4.1.4/lib/active_record/associations.rb:1580:in `has_and_belongs_to_many'
from /Users/Kevin/Sites/gemgento/app/models/gemgento/product.rb:21:in `<class:Product>'

1 个答案:

答案 0 :(得分:20)

在Rails 4.1中搜索HABTM的任何记录更改后,我找不到任何内容。 4.0中也没有弃用警告。事实证明,:class_name必须定义为String。

module Gemgento
   class Product < ActiveRecord::Base
      has_and_belongs_to_many :stores, -> { distinct }, join_table: 'gemgento_stores_products', class_name: 'Gemgento::Store'
   end
end

此更改不会影响任何其他关联。但是从现在开始确保始终使用字符串可能是件好事。