单个页面中同一模型的多种形式 [英] Multiple forms for the same model in a single page

查看:61
本文介绍了单个页面中同一模型的多种形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 rap歌词解释网站的首页上,用户可以尝试解释具有挑战性的内容:

On the front page of my rap lyrics explanation site, there's a place where users can try explaining a challenging line:

替代文本http://dl.dropbox.com/u/2792776/screenshots/2010-02-06_1620.png

这是我用来生成此代码的部分内容:

Here's the partial I use to generate this:

<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(导致名称冲突)

However, putting more than one of these on a single page is problematic because Rails automatically gives each form an ID of new_feedback, and each field an ID like feedback_body (leading to name collisions)

很显然,我可以在表单及其所有字段中添加类似:id => ''的内容,但这似乎有点重复.最好的方法是什么?

Obviously I could add something like :id => '' to the form and all its fields, but this seems a tad repetitive. What's the best way to do this?

推荐答案

如果您不想更改输入名称或模型结构,则可以使用id选项使表单ID唯一,而namespace选项,以使您的输入ID唯一:

If you don't want to change your input names or your model structure, you can use the id option to make your form ID unique and the namespace option to make your input IDs unique:

<%= form_for Feedback.new(...), 
    id: "annotation_#{annotation.id}_feedback"
    namespace: "annotation_#{annotation.id}" do |f| %>

这样,我们的表单ID是唯一的,即annotation_2_feedback,并且还会添加前缀,例如annotation_2_,用于通过f创建的每个输入.

That way our form ID is unique, i.e. annotation_2_feedback and this will also add a prefix, e.g. annotation_2_, to every input created through f.

这篇关于单个页面中同一模型的多种形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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