Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested forms in rails - accessing attribute in has_many relation

Tags:

I have a user and a profile model. One user can have many profiles. I need to access only one information from the profiles section (viz the phone number) in my user model during the user creation process. Hence I'm trying to get it done through attr_accessible. My user.rb looks like this.

has_many :profiles attr_accessible :handle, :email, :password, :profile_mobile_number attr_accessor : :profile_mobile_number 

The problem that I'm facing is that when I try to call the getter method profile_mobile_number in a method in user.rb (the method is private, though I think it doesn't matter), I'm getting a null value. I use the following in my users/new.html.erb form

My question is what is the right way to do this? Should I use <% f.fields_for :profile do |ff| -%> or <% f.fields_for :profiles do |ff| -%> (notice that the second one is plural). When I use the plural :profiles, I don't even see the fields on the form. What am I missing here? And what is the tense that needs to be used in model user.rb? :profile_phone_number or :profiles_phone_number? Thanks.

like image 799
Swamy g Avatar asked Feb 12 '10 01:02

Swamy g


2 Answers

You could do something like the following:

<% form_for @user, :url => { :action => "update" } do |user_form| %>   ...   <% user_form.fields_for :profiles do |profiles_fields| %>      Phone Number: <%= profiles_fields.text_field :profile_mobile_number %>    <% end %> <% end %> 

But since you already have an association, then might as well use 'accepts_nested_attributes_for'

like image 54
Pran Avatar answered Sep 25 '22 08:09

Pran


You should watch RailsCasts Nested Model Form.
thanks Ryan Bates great work.

like image 36
allenwei Avatar answered Sep 22 '22 08:09

allenwei