Nested forms: Can you access the object from within fields_for?

7 views
Skip to first unread message

John Grimes

unread,
Apr 11, 2010, 10:13:42 PM4/11/10
to rubyonra...@googlegroups.com
Hi all,

Say I had the following form:

<% form_for @user do |f| %>
<%= f.error_messages %>
<% f.fields_for :friends do |friends| %>
<%= friends.text_field :relationship_to_you %>
<% end %>
<p><%= f.submit "Submit" %></p>
<% end %>

Is it possible to access the current object within that fields_for
block as it iterates through?

For example, could I add another line that looked something like this
with the friend's name:

<% form_for @user do |f| %>
<%= f.error_messages %>
<% f.fields_for :friends do |friends| %>
<label><%= friend.name %></label>
<%= friends.text_field :relationship_to_you %>
<% end %>
<p><%= f.submit "Submit" %></p>
<% end %>

Thanks for your help.

John Grimes

toami...@gmail.com

unread,
Apr 12, 2010, 8:31:16 AM4/12/10
to Ruby on Rails: Talk
Yes u can with
friend.object.name

John Grimes

unread,
Apr 12, 2010, 11:49:14 PM4/12/10
to rubyonra...@googlegroups.com
That works perfectly, thanks!

Just to clarify for anyone else reading this, code such as this should work:

<% form_for @user do |f| %>
 <%= f.error_messages %>
 <% f.fields_for :friends do |friends| %>
   <label><%= friends.object.name %></label>

   <%= friends.text_field :relationship_to_you %>
 <% end %>
 <p><%= f.submit "Submit" %></p>
<% end %>
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonra...@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-ta...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.


Reply all
Reply to author
Forward
0 new messages