3

我有兩個類,數量和免費的東西:NameError:未初始化不斷 - ActiveRecord的

class Number < ActiveRecord::Base 
    belongs_to :account 
    has_many :freebies 

end 

class Freebie < ActiveRecord::Base 
    belongs_to :number 

    attr_accessible :name, :data 

    has_attached_file :data, :path => "freebies/:id_partition/:filename" 

    def to_s 
    name 
    end 
end 

我的所有其他類用的has_many和belongs_to的關係做工精細,但當我打電話是這樣的:

n = Number.last 
n.freebies.create 

我得到這個錯誤:

NameError: uninitialized constant Number::Freeby 
    from /Users/Robby/.rvm/gems/ruby-1.9.2-p320/gems/activerecord-3.2.8/lib/active_record/inheritance.rb:111:in `compute_type' 
    from /Users/Robby/.rvm/gems/ruby-1.9.2-p320/gems/activerecord-3.2.8/lib/active_record/reflection.rb:172:in `klass' 
    from /Users/Robby/.rvm/gems/ruby-1.9.2-p320/gems/activerecord-3.2.8/lib/active_record/associations/collection_association.rb:148:in `transaction' 
    from /Users/Robby/.rvm/gems/ruby-1.9.2-p320/gems/activerecord-3.2.8/lib/active_record/associations/collection_association.rb:431:in `create_record' 
    from /Users/Robby/.rvm/gems/ruby-1.9.2-p320/gems/activerecord-3.2.8/lib/active_record/associations/collection_association.rb:119:in `create' 
    from /Users/Robby/.rvm/gems/ruby-1.9.2-p320/gems/activerecord-3.2.8/lib/active_record/associations/collection_proxy.rb:46:in `create' 
    from (irb):20 
    from /Users/Robby/.rvm/gems/ruby-1.9.2-p320/gems/railties-3.2.8/lib/rails/commands/console.rb:47:in `start' 
    from /Users/Robby/.rvm/gems/ruby-1.9.2-p320/gems/railties-3.2.8/lib/rails/commands/console.rb:8:in `start' 
    from /Users/Robby/.rvm/gems/ruby-1.9.2-p320/gems/railties-3.2.8/lib/rails/commands.rb:41:in `<top (required)>' 
    from script/rails:6:in `require' 
    from script/rails:6:in `<main>' 

我有一些其他問題免費贈品CLA ss,因爲它以ie結尾,並且Rails試圖讓單數版本「Freeby」而不是Freebie。不過,我不知道爲什麼這不起作用。

回答

2

Rails會自動嘗試從單數形式推斷單詞的複數形式,反之亦然。您可能想要考慮覆蓋默認的變形規則。

嘗試類似於this Stackoverflow question中的答案。

+1

是的,這是它!我將以下內容放入我的初始化程序/ inflections.rb文件中: 'ActiveSupport :: Inflector.inflections do | inflect | inflect.irregular'freebie','freebies' end' 現在我可以打電話給n.freebies.create罰款。 感謝您指點我! – user1839823

+0

沒問題。很高興我能幫上忙! – Zajn

0
"n.freebie.build" 

做同樣的事情,你正試圖做。 讓我知道它是否有效。

相關問題