ruby-on-rails – 单个页面中同一模型的多个表单

在我的 rap lyrics explanation site的首页上,用户可以尝试解释具有挑战性的产品线:

alt text http://dl.dropbox.com/u/2792776/screenshots/2010-02-06_1620.png

这是我用来生成这个的部分:

<div class="stand_alone annotation" data-id="<%= annotation.id %>">
  <%= song_link(annotation.song,:class => :title) %>

  <span class="needs_exegesis"><%= annotation.referent.strip.gsub(/\n/,"\n <br />") %></span>

  <% form_for Feedback.new(:annotation_id => annotation.id,:created_by_id => current_user.try(:id),:email_address => current_user.try(:email)),:url => feedback_index_path,:live_validations => true do |f| %>
    <%= f.hidden_field :annotation_id %>
    <%= f.hidden_field :created_by_id %>
    <p style="margin-top: 1em">
        <%= f.text_area :body,:rows => 4,:style => 'width:96%',:example_text => "Enter your explanation" %>
    </p>
    <p>
      <% if current_user %>
        <%= f.hidden_field :email_address %>
      <% else %>
        <%= f.text_field :email_address,:example_text => "Your email address" %>
      <% end %>
      <%= f.submit "Submit",:class => :button,:style => 'margin-left: .1em;' %>
    </p>
  <% end %>
</div>

但是,将多个这些放在一个页面上是有问题的,因为Rails会自动为每个表单提供一个new_feedback的ID,每个字段都有一个像feedback_body这样的ID(导致名称冲突)

显然我可以添加类似:id => ”到形式及其所有领域,但这似乎有点重复.最好的方法是什么?

解决方法

如果您不想更改输入名称或模型结构,可以使用id选项使表单ID唯一,并使用名称空间选项使输入ID唯一:
<%= form_for Feedback.new(...),id: "annotation_#{annotation.id}_feedback"
    namespace: "annotation_#{annotation.id}" do |f| %>

这样,我们的表单ID是唯一的,即annotation_2_feedback,这也将添加一个前缀,例如annotation_2_,通过f创建的每个输入.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...