Re: Problems with has_one - not saving association

Jarkko Laine
2005-06-15T06:32:53Z

On 15.6.2005, at 03:49, Ben Jackson wrote:

> Here are my models:
>
> class Person < ActiveRecord::Base
> 	has_one :user
> 	# class code...
>
> class User < ActiveRecord::Base
> 	# class code...
>
> And my controller:
>
> class PersonController < ApplicationController
> 	def create
> 		unless logged_in?
> 			@user = User.new(@params[:user])
> 		else
> 			@user = @session[''user'']
> 		end
> 		@person = Person.new(@params[:person])
> 		@person.user = @user
> 		render_text @person.user_id
> 	end
> end
>
> @user.id is tracing out as expected, but the render_text call keep
> spitting out 0. What am I doing wrong?

There is no such thing as @person.user_id if a person has_one :user. In
this case the foreign key field should be person_id and reside in users
table.

Amy Hoy''s AR association cheat sheet might come in handy:
http://www.slash7.com/cheats/activerecord_cheatsheet.pdf

The thing to remember is that the foreign key is always in the class
that "belongs_to" something. This is obvious with has_many-belongs_to
(1-to-many) relationships but also the case with has_one-belongs_to
(1-to-1) stuff.

//jarkko

--
Jarkko Laine
http://jlaine.net
http://odesign.fi


_______________________________________________
Rails mailing list
Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org