Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

loops - Rails: fields_for with index?

Is there a method (or way to pull off similar functionality) to do a fields_for_with_index?

Example:

<% f.fields_for_with_index :questions do |builder, index| %>  
  <%= render 'some_form', :f => builder, :i => index %>
<% end %>

That partial being rendered needs to know what the current index is in the fields_for loop.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The answer is quite simple as the solution is provided within Rails. You can use f.options params. So, inside your rendered _some_form.html.erb,

Index can be accessed by:

<%= f.options[:child_index] %>

You don't need to do anything else.


Update: It seems that my answer wasn't clear enough...

Original HTML File:

<!-- Main ERB File -->
<% f.fields_for :questions do |builder| %>  
  <%= render 'some_form', :f => builder %>
<% end %>

Rendered Sub-Form:

<!-- _some_form.html.erb -->
<%= f.options[:child_index] %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...