Rails 3 中的嵌套模型错误

发布于 2024-10-03 08:49:00 字数 673 浏览 0 评论 0原文

我有两个模型应用程序和联系人。应用程序与联系人具有 has_one 关系。我已在联系人的应用程序模型中声明了 Accepts_nested_attributes_for 子句。现在,在 apps_controller 中,如果我在 app 对象上使用 build 方法,即使我已经声明了关系,我也会收到 nil 类的错误。

App.rb

class App < ActiveRecord::Base
  has_one :contact_person, :dependent => :destroy
  accepts_nested_attributes_for :contact_person
end

ContactPerson.rb

class ContactPerson < ActiveRecord::Base
  belongs_to :app
end

apps_controller.rb

def new
  @app = App.new
  @app.contact_person.build
end

请您指出我是否做错了什么。我以前使用过嵌套模型,但没有遇到过这个错误。

I have two models App and Contact. App has a has_one relationship with Contact. I have declared the accepts_nested_attributes_for clause in the App model for Contact. Now, in the apps_controller, if I use the build method on the app object, I get an error for the the nil class, even though I had declared the relationship.

App.rb

class App < ActiveRecord::Base
  has_one :contact_person, :dependent => :destroy
  accepts_nested_attributes_for :contact_person
end

ContactPerson.rb

class ContactPerson < ActiveRecord::Base
  belongs_to :app
end

apps_controller.rb

def new
  @app = App.new
  @app.contact_person.build
end

Could you please point me out whether am I doing anything incorrectly. I have used nested models before but have not encountered this error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

追风人 2024-10-10 08:49:00

我应该使用 @app.build_contact_person 而不是 @app.contact_person.build。这样,就成功了:)

I am supposed to use @app.build_contact_person instead of @app.contact_person.build. In this way, it worked :)

许一世地老天荒 2024-10-10 08:49:00

声明关联不会自动创建它:

class App < ActiveRecord::Base
  has_one :contact_person, :dependent => :destroy
  accepts_nested_attributes_for :contact_person
  # Adding this line should work
  after_create { self.contact_person = ContactPerson.new }
end

Declaring association does not automatically creates it:

class App < ActiveRecord::Base
  has_one :contact_person, :dependent => :destroy
  accepts_nested_attributes_for :contact_person
  # Adding this line should work
  after_create { self.contact_person = ContactPerson.new }
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文