3

我有两个课程,数字和免费赠品:

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>'

我在 Freebie 类上遇到了一些其他问题,因为它以 ie 结尾,而且 Rails 试图制作单数版本“Freeby”而不是 Freebie。不过,我不确定为什么这不起作用。

4

2 回答 2

2

Rails 会自动尝试从单数形式推断单词的复数形式,反之亦然。您可能需要考虑覆盖默认的变形规则。

尝试类似于此 Stackoverflow 问题中的答案。

于 2012-11-21T16:43:49.707 回答
0
"n.freebie.build" 

做你想做的同样的事情。让我知道它是否有效。

于 2012-11-21T17:15:21.260 回答