Rails:带索引的fields_for? [英] Rails: fields_for with index?

查看:63
本文介绍了Rails:带索引的fields_for?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在执行fields_for_with_index的方法(或实现类似功能的方法)?

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

示例:

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

正在渲染的部分内容需要知道fields_for循环中的当前索引.

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

推荐答案

实际上,按照Rails文档的详细说明,这将是更好的方法:

This would actually be a better approach, following Rails documentation more closely:

<% @questions.each.with_index do |question,index| %>
    <% f.fields_for :questions, question do |fq| %>  
        # here you have both the 'question' object and the current 'index'
    <% end %>
<% end %>

发件人: http://railsapi.com/doc/rails-v3.0.4/classes/ActionView/Helpers/FormHelper.html#M006456

还可以指定 要使用的实例:

It’s also possible to specify the instance to be used:

  <%= form_for @person do |person_form| %>
    ...
    <% @person.projects.each do |project| %>
      <% if project.active? %>
        <%= person_form.fields_for :projects, project do |project_fields| %>
          Name: <%= project_fields.text_field :name %>
        <% end %>
      <% end %>
    <% end %>
  <% end %>

这篇关于Rails:带索引的fields_for?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆