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

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 %>

<%= f.submit "Submit" %>

<% 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| %>
<%= friend.name %>
<%= friends.text_field :relationship_to_you %>
<% end %>

<%= f.submit "Submit" %>

<% end %>

Thanks for your help.

John Grimes

Yes u can with
friend.object.name

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| %>
<%= friends.object.name http://friend.name %>
<%= friends.text_field :relationship_to_you %>
<% end %>

<%= f.submit "Submit" %>

<% end %>

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs