Forum: Ruby on Rails Can't create has_one record

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
87f4477dced7fcff3ac2154e88d53210?d=identicon&s=25 T. B. (vineire77)
on 2008-11-12 23:10
Hello all. I have the following code in my Accounts controller:

@account = Account.create(params[:account])
@website = @account.websites.create(params[:website])
@contact = @account.contact.create(params[:contact])

My Account model has_one :contact and my Contact belongs_to :account,
yet I get the following error:

NoMethodError: You have a nil object when you didn't expect it!
The error occurred while evaluating nil.create


- - - - - -


I've scoured the documentation and can't find where I'm mucking things
up. Any help is greatly appreciated!

-tb
5acf8e6be07793d22e24d8eb24a0e043?d=identicon&s=25 reHa (Guest)
on 2008-11-12 23:30
(Received via mailing list)
@account = Account.create(params[:account])

now you have new account - contact is empty

@account.contact is nil -> calling @account.contact.create is the same
as calling nil.create

try:

@account = Account.create(params[:account])
@account.contact = Contact.create(params[:contact])
Ef3aa7f7e577ea8cd620462724ddf73b?d=identicon&s=25 Rob Biedenharn (Guest)
on 2008-11-12 23:53
(Received via mailing list)
On Nov 12, 2008, at 5:29 PM, reHa wrote:
> @account.contact = Contact.create(params[:contact])
>
> On Nov 12, 11:10 pm, "T. B." <rails-mailing-l...@andreas-s.net> wrote:
>> Hello all. I have the following code in my Accounts controller:
>>
>> @account = Account.create(params[:account])
>> @website = @account.websites.create(params[:website])
>> @contact = @account.contact.create(params[:contact])

@contact = @account.create_contact(params[:contact])

>> things
>> up. Any help is greatly appreciated!
>>
>> -tb



It's right there in the docs for has_one.  Compare to the similar
semantics for has_many associations that you're obviously familiar with.

http://api.rubyonrails.org/classes/ActiveRecord/As...

-Rob

Rob Biedenharn    http://agileconsultingllc.com
Rob@AgileConsultingLLC.com
This topic is locked and can not be replied to.