存在关联时无法保存模型对象

时间:2012-12-03 10:38:46

标签: ruby-on-rails ruby activesupport model-associations

在我的rails应用程序中,当存在关联时,我无法保存模型对象。 我正在使用mongo作为db。  简要说明:

我有一个模型对象,

@obj1 = User.create(name: "name1")

当我做@ obj1.save时,它运行正常。现在我加了一个关系说,

has_many :offices

然后我尝试用新条目保存相同的对象。

@obj1 = User.create(name: "name2")

我收到类似

的错误
 /gems/activesupport-3.2.9/lib/active_support/inflector/methods.rb:230:in `block in constantize'
 gems/activesupport-3.2.9/lib/active_support/inflector/methods.rb:229:in `each'

编辑:

完整错误跟踪:

NameError: uninitialized constant Office
            from /home/workspace/.rvm/gems/ruby-1.9.3-p286@cv_app/gems/activesupport-3.2.9/lib/active_support/inflector/methods.rb:230:in `block in constantize'
            from /home/workspace/.rvm/gems/ruby-1.9.3-p286@cv_app/gems/activesupport-3.2.9/lib/active_support/inflector/methods.rb:229:in `each'
            from /home/workspace/.rvm/gems/ruby-1.9.3-p286@cv_app/gems/activesupport-3.2.9/lib/active_support/inflector/methods.rb:229:in `constantize'
            from /home/workspace/.rvm/gems/ruby-1.9.3-p286@cv_app/gems/activesupport-3.2.9/lib/active_support/core_ext/string/inflections.rb:54:in `constantize'

2 个答案:

答案 0 :(得分:0)

在您的用户模型中

class User < ActiveRecord::Base
  has_many :offices 
end

在您的办公室模型中

class Office < ActiveRecord::Base
  belongs_to :user
end

现在,试试这个

@user = User.new
@user.name = "xyz"
@user.save

关系

@user = User.offices.build

答案 1 :(得分:0)

检查办公室模型和表是否已创建。这两个被创建它不会给出这种错误。