Nested Models Error in Rails 3
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开发者_如何学C_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.
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:
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
精彩评论