The following definition was working in Rails 4.0.x and lower:
module Gemgento
class Product < ActiveRecord::Base
has_and_belongs_to_many :stores, -> { distinct }, join_table: 'gemgento_stores_products', class_name: Gemgento::Store
end
end
However, after upgrading to Rails 4.1.x, I started to receive the following error whenever the Gemgento::Product
class was initialized.
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>'
After searching for any documented changes to HABTM in Rails 4.1, I couldn't find anything. There were no deprecation warnings in 4.0 either. It turns out that :class_name
must be defined as a 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
This change does not affect any other association. But it is probably good to make sure a string is always used from now on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With