简体   繁体   English

Rails-如何呈现两个相同但具有不同元素ID的表单?

[英]Rails - how to render two identical forms but with different element IDs?

I would like to have two almost identical forms on a single page and use a partial for generating both with a render call. 我想在单个页面上使用两种几乎相同的形式,并使用一部分通过render调用生成两种形式。

<%= render 'form_template', data: @categories_one %>
<%= render 'form_template', data: @categories_two %>

The problem lies in their only difference - both forms use f.collection_select to provide dropboxes with categories for the user. 问题在于它们唯一的区别-两种形式都使用f.collection_select为用户提供具有类别的保管箱。

<%= f.collection_select :category_id, data, :id, :name %>

which creates two different forms with identical IDs for the SELECT tag, breaking my forms, and I would like to avoid that. 它为SELECT标记创建两个具有相同ID的不同表单,破坏了我的表单,我希望避免这种情况。 But how can I do that? 但是我该怎么办呢?

You can pass :namespace parameter to the form_for 您可以将:namespace参数传递给form_for

A namespace for your form to ensure uniqueness of id attributes on form elements. 表单的名称空间,以确保表单元素上id属性的唯一性。 The namespace attribute will be prefixed with underscore on the generated HTML id. 命名空间属性将在生成的HTML ID上带有下划线前缀。

If you look at the documentation for collection_select , you'll see that its last argument is for HTML options. 如果查看collection_select文档 ,您会看到它的最后一个参数是HTML选项。 So you can do this: 因此,您可以执行以下操作:

<%= f.collection_select :category_id, data, :id, :name, {}, {:id => "different_css_id"} %>

Since you said this is called within a partial though, from your identical render calls, you can pass along a variable to toggle this behaviour. 因为您说过在同一个渲染调用中部分调用了此方法,所以您可以传递一个变量来切换此行为。

# Render calls
<%= render 'form_template', data: @categories_one %>
<%= render 'form_template', data: @categories_one, :locals => {:use_other_id => true} %>

And then use that flag in your partial. 然后在您的局部使用该标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM