Creating unique id for <fieldset> when using form_for Rails Nested Model Form

北战南征 提交于 2019-12-05 18:12:28
Cyril Duchon-Doris

If you are using ryanb nested_form gem :

Use f.index instead. And make sure that you pass every different form_builder in your partials.

For example if you do

<%= main_form.fields_for :nested1_items do |nested1_form| %>
    <%= render partial 'main/nested1_fields', nested1_form: nested1_form %>
<% end %>

_nested1_fields

<fieldset id="nested1-<%= nested1_form.index %>-items">

See my answer in this question.

Why not just use the f.object passed in to both partials?

<% fieldset_id = "#{f.object.class.underscore}_#{f.object.id}" %>
<fieldset id='<%= fieldset_id %>'>
...

I had a similar issue, and I solve it using the time in seconds, and pass it to every where I needed.

For example:

in the controller

def something
  # First idea
  @dynid = Time.now.to_i
  ...
  # Second idea: store it in the session
  session[:dynid] = Time.now.to_i
  ...
end

in your view

<fieldset id="#{@dynid}">
<!-- or in case @dynid is out of reach, then use the session[:dynid] -->
<fieldset id="#{session[:dynid]}">

The session[:dynid} will still works even with ajax rendered code.

I hope this helps you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!