Rails 3 中的嵌套模型错误
我有两个模型应用程序和联系人。应用程序与联系人具有 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我应该使用
@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 :)声明关联不会自动创建它:
Declaring association does not automatically creates it: