简体   繁体   中英

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 '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 :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. But how can I do that?

You can pass :namespace parameter to the form_for

A namespace for your form to ensure uniqueness of id attributes on form elements. The namespace attribute will be prefixed with underscore on the generated HTML id.

If you look at the documentation for collection_select , you'll see that its last argument is for HTML options. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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