【问题标题】:How to override default id value in Rails Form helper methods?如何在 Rails Form 辅助方法中覆盖默认 id 值?
【发布时间】:2013-06-17 14:54:42
【问题描述】:

所以,我正在使用 Rails 和 Ajax 制作一个待办事项列表应用程序。我的“lists/show.html.erb”文件中的每个待办事项都有一个表格。这是其中的一些代码:

<h3>Unfinished Tasks</h3>
<div class="tasks" id="incomplete_tasks">
  <% @list.tasks.incomplete.each do |task| %>
      <%= form_for [current_user, @list, task], remote: true do |f| %>
          <%= f.label :completed, class: 'checkbox' do %>
             <%= f.check_box :completed %>
             <%= task.description %>
          <% end %>
         <%= f.submit "Update" %>        <!--We hide this button in jquery-->
      <% end %>
  <% end %>
</div>

这样做的问题是在同一个页面中创建了多个表单并且具有相同 id 的输入复选框,即所有表单中的输入字段(复选框)具有由 Rails 自动创建的相同输入 id。这使得标签标签无用,因为我们需要在 for 属性中使用唯一的 id。

<label for="">

那么,有没有办法通过添加前缀来更改默认 id 创建,以便每个表单的输入标签都是唯一的?既然这是一个很常见的问题,有没有“Rails 方式”来解决这个“标签”问题?

P.S:这是http://goo.gl/bB9D6的后续问题

在旁注中,我如何向 Railscasts(Ryan Bates) 发送错误报告(这就是我获得此代码的地方)。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    好的,这很简单。我只是使用了以下代码:

      <%= form_for [current_user, @list, task], remote: true do |f| %>
          <%= f.label 'completed_'+task.object_id.to_s, class: 'checkbox' do %>
              <%= f.check_box :completed ,id:'task_completed_'+task.object_id.to_s%>   <!--have overridden default id because label works only if there is a unique id in each page-->
              <%= task.description %>
          <% end %>
          <%= f.submit "Update" %>        <!--We hide this button in jquery-->
      <% end %>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 2012-08-12
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      • 2021-11-03
      • 1970-01-01
      • 2011-03-31
      相关资源
      最近更新 更多