Has One - Belongs to question

I have a User model that has_one BillingProfile and BillingProfile belongs to a User. How do I retrieve the billing profile corresponding to that particular user? TIA.

class User < ActiveRecord::Base has_one :billing_profile end

class BillingProfile < ActiveRecord::Base belongs_to :user end

user = User.find(:first) user.billing_profile

I generated the User model by using RESTful Authentication plugin. I ran the ./script/generate authenticated user sessions command and it generated the migration for users table. I ran the rake db:migrate. I also defined the has_one and belongs_to in the User and BillingProfile class.

My question is currently the BillingProfile table does not have the user_id foreign key. Do I need to create a separate migration for that? Thanks again.

Yes, the billing_profiles table must have a column of type integer, named user_id. It will act as a foreign key to the users table.

In my User object I am saving the login id of the user, (after the user logs in successfully)

session[:user_key] = user.id

In my BillingProfile show method, I want to retrieve the billling profile for that particular user:

billing_profile = BillingProfile.find(:first, :conditions => "user_id=‘user_key’ ")

Is the above code the right way to do it? TIA.

The way I would probably do it is something like:

@user = User.find(session[:user_key]) @billing_profile = @user.billing_profile

The first line sets the @user instance variable the User object with id session[:user_key]. The second line grabs a BillingProfile object, in particular, the one with user_id = @user.id . It would probably be a good exercise to look at the SQL queries generated for these calls.

That’s the way to do it…

but you might consider using eager loading so you avoid an extra DB call (if you can)

@user = User.find(session[:user_key], :include=>[:billing_profile]) @billing_profile = @user.billing_profile