在 rails 上使用 ruby 以 html 形式循环

Loop in a html form erb using ruby on rails

我想构建一个表单,其中字段名称为 type1、type2、type3 ...到 type10、size1、size2、size3...到 size10 等

我需要在文本字段中呈现它们,以便用户可以为它们输入值。 我不想手动键入它们中的每一个,因为必须有一些我可以使用的循环迭代器。我知道每种方法,但我只想创建一个循环来循环遍历 type1 到 type10。我怎样才能做到这一点?

 <div class="field" id="type1">
    <%= f.label :type1 %>
    <%= f.select :type1 ,['text','barcode']%>
 </div> 

 <div class="field" id="type2">
    <%= f.label :type2 %>
    <%= f.select :type2 ,['text','barcode']%>
 </div> 

<div class="field" id="barcode_type1">
    <%= f.label :barcode_type1 %>
    <%= f.text_field :barcode_type1 %>
    </div> 

<div class="field" id="barcode_type2">
    <%= f.label :barcode_type2 %>
    <%= f.text_field :barcode_type2 %>
    </div> 

有什么建议吗?

更新:

$(document).on('turbolinks:load', function(){


if ($('#type1').find('option:selected').val() != "barcode")
  {
   $('#barcode_type1').hide();
   $("#barcode_type1").attr('disabled','disabled');
  }
  else
  {
     $("#barcode_type1").removeAttr('disabled');
     $('#barcode_type1').show();
  }

$('#type1').on('change', function(){
  if ($('#type1').find('option:selected').val() != "barcode")
  {
   $('#barcode_type1').hide();
   $("#barcode_type1").attr('disabled','disabled');
  }
  else
  {
     $("#barcode_type1").removeAttr('disabled');
     $('#barcode_type1').show();
  }
})

});

如果我将 div id 设置为 id = "type1",JS 运行良好。如果我使用循环使用 "type#{i}",JS 停止工作。有没有解决办法。 我还想在 Javascript 中将类型 1 循环到类型 10,将 barcode_type1 循环到 barcode_type10。有没有办法有效地做到这一点。

您可以使用:

<% for i in 1..10 do %>
  <div class="field" id="type#{i}"
    <%= f.label "type#{i}" %>
    <%= f.select "type#{i}", ["text", "barcode"] %>
  </div>
<% end %>

您也可以像您提到的那样使用每个循环,但不能使用 for 循环。

<% (1..10).each do |i| %>
    <div class="field" id="type#{i}">
        <%= f.label "type#{i}" %>
        <%= f.select "type#{i}" ,['text','barcode']%>
    </div> 
    <div class="field" id="barcode_type#{i}">
        <%= f.label "barcode_type#{i}" %>
        <%= f.text_field "barcode_type#{i}" %>
    </div> 
<% end %>