2014-07-07 9 views
8

następująca definicja pracowała w Rails 4.0.x oraz dolna:Rails 4.1.x HABTM niezdefiniowana metoda „foreign_key”

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

Jednak po uaktualnieniu do Rails 4.1.x, zacząłem się następujący komunikat o błędzie po zainicjowaniu klasy Gemgento::Product.

NoMethodError: undefined method `foreign_key' for #<Class:0x007f870f18e668> 
from /Users/Kevin/.rvm/gems/[email protected]/gems/activerecord-4.1.4/lib/active_record/dynamic_matchers.rb:26:in `method_missing' 
from /Users/Kevin/.rvm/gems/[email protected]/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/[email protected]/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/[email protected]/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>' 

Odpowiedz

18

Po wyszukaniu udokumentowanych zmian w HABTM w Railsach 4.1, nie mogłem nic znaleźć. Nie było również ostrzeżeń o wycofaniu w wersji 4.0. Okazuje się, że :class_name musi być zdefiniowany jako łańcuch.

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

Ta zmiana nie wpływa na żadne inne powiązanie. Ale prawdopodobnie dobrze jest upewnić się, że ciąg jest zawsze używany od teraz.

+1

Dzięki, zaoszczędziło mi to wiele kłopotów. –

+1

Chciałbym również zauważyć, że warto użyć 'class: Gemgento :: Store' lub' class_name: Gemgento :: Store.name', aby uchronić się przed błędami. – faron

Powiązane problemy