使用Cocoon Gem构建Rails动态表单时表单及提交按钮重复显示问题排查
问题排查结果
根因
你的表单代码将#work_experiences容器、新增按钮、提交按钮全部包进了f.fields_for :work_experiences的循环体中。fields_for会根据当前关联的work_experiences记录条数循环渲染内部代码,只要@user存在至少1条已保存的工作经历记录,这些元素就会被重复渲染多次,导致出现重复的表单和按钮。
修复后的表单代码
<%= form_with model: @user do |f| %> <!-- 容器放在循环外部,只需要渲染一次 --> <div id='work_experiences'> <!-- 仅将字段局部模板的渲染逻辑放在fields_for循环内 --> <%= f.fields_for :work_experiences do |work_experience| %> <%= render "work_experience_fields", f: work_experience %> <% end %> </div> <!-- 新增按钮、提交按钮都放在循环外部,只渲染一次 --> <%= link_to_add_association 'add more work experience', f, :work_experiences, data: { association_insertion_node: '#work_experiences', association_insertion_method: :append } %> <%= f.submit 'Update Work Experience' %> <% end %>
其他需修正的潜在问题
- Gemfile中gem名拼写错误,正确写法为
gem 'cocoon',你当前写的gem coccon多了一个字符c,会导致gem安装、更新异常 - 局部模板
_work_experience_fields中job_title对应的label属性错写为job_tile,会导致点击label无法正确聚焦到对应输入框
内容的提问来源于stack exchange,提问作者r3b00t
相关产品推荐
相关产品推荐

