views:

36

answers:

1

Hi everyone,

I'm really new at Ruby On Rails and I'm working with a baseApp that comes with the login and user registration functionalities. It also creates an empty profile for a user when they sign up.

Then, I've created a migration to add fields to the profiles table, such as firstName, gender, state, country, etc.

What I'd like to do, is to show those fields at the registration form and then save them on the profiles table. How can I do this?

Thanks,

Brian

A: 

accepts_nested_attributes_for provides everything you need.

So long as you've st up your user to have one profile you're just about good to go.

Add accepts_nested_attributes_for :profile to the User model. Then set up your form to be something like this:

<% form_for :user do |f| %>
  ...
  User model fields
  ... 
  <% @user.build_profile if @user.profile.nil? %>
  <% f.fields_for :profile do |p| %>
    <%= p.label :first_name %>
    <%= p.text_field :first_name %>
    ...
    Profile model fields
    ...
  <% end %>
<% end %>

The controller needs no modification.

Read up on the nested form section of FormHelper for more details.

EmFi
Thanks for the answer.When I add the <% @user.profile.build %> line it throws me the following exception:"You have a nil object when you didn't expect it!The error occurred while evaluating nil.build"I've already added the line accepts_nested_attributes_for :profile to the User model, but I don't know what's going on.
Brian Roisentul
Sorry that should've been build_profile, fixed now.
EmFi
So, should it be <% @user.profile.build_profile %>?Doesn't work either. Maybe I'm missing something else.
Brian Roisentul
I confused `@user.profiles.build` for a has\_many relationship with `@user.build_profile` for a has\_one relationship while writing my answer. The answer was edited to correct this. I guess you didn't notice it.
EmFi
Oh, you're right.Thank you.
Brian Roisentul
I still can't make the profile's fields to be saved at mySQL. I don't know why. Can anyone help me with this? Thank you.
Brian Roisentul
Does your user model contain attr\_accessible anywhere? If so you'll need to add :profile\_attributes to the list of accessible attributes?
EmFi
Yes. I've already fixed it by changing something at the controller. Thank you!
Brian Roisentul