无模型关联的Rails表单如何编写?仅用于前端JS计算与模态框触发
你的表单代码分析与优化建议
嘿,你的代码能正常运行这点很棒!不过咱们可以做一些优化,让它更贴合你的需求(毕竟不需要提交到后端),同时也让语法更简洁合理。
现有代码里的冗余点
你当前用了form_tag( '/welcome/index', post: true, remote: true),但这些属性其实都是多余的:
'/welcome/index':指定了表单提交的后端路径,但你根本不需要提交到后端post: true:设置了请求方法,同样不需要remote: true:开启了Rails的AJAX表单提交,这也和你的需求无关
虽然这些冗余属性不会影响当前功能(因为你的按钮是type="button",不会触发表单提交),但留着它们可能会在后续维护中造成误解,甚至如果不小心把按钮改成type="submit",就会触发不必要的后端请求。
语法正确性确认
你的表单元素写法是完全正确的:
text_field_tag的参数(名称、默认值、placeholder、class、id)都符合Rails的语法规范- 触发模态框的按钮设置了
type="button"、data-toggle="modal"和data-target="#savingsModal",这完全符合Bootstrap模态框的触发要求
优化后的代码
这里给你简化后的版本,去掉所有不必要的后端交互属性,同时保留你需要的功能:
<%= form_tag('#', method: :get, html: { class: "your-form-class" }) do %> <h5 class="label">Estimated new home cost?</h5> <%= text_field_tag :price, nil, placeholder: "ex. 100,000", class: "form-control form-control-lg", id: 'price' %> <h5 class="label">Estimated payment for a new home?</h5> <%= text_field_tag :mortgage, nil, placeholder: "ex. 1,200", class: "form-control form-control-lg", id: 'mortgage' %> <h5 class="label">Current Monthly Rent?</h5> <%= text_field_tag :rent, nil, placeholder: "ex. 800", class: "form-control form-control-lg", id: 'rent' %> <button type="button" class="btn btn-success btn-lg" data-toggle="modal" data-target="#savingsModal"> See how quickly you can buy a home </button> <% end %>
或者如果你连form标签都不需要(因为只是用来包裹输入框,没有表单提交需求),甚至可以直接去掉form_tag,只用div包裹输入框和按钮,这样更简洁:
<div class="your-form-wrapper"> <h5 class="label">Estimated new home cost?</h5> <%= text_field_tag :price, nil, placeholder: "ex. 100,000", class: "form-control form-control-lg", id: 'price' %> <h5 class="label">Estimated payment for a new home?</h5> <%= text_field_tag :mortgage, nil, placeholder: "ex. 1,200", class: "form-control form-control-lg", id: 'mortgage' %> <h5 class="label">Current Monthly Rent?</h5> <%= text_field_tag :rent, nil, placeholder: "ex. 800", class: "form-control form-control-lg", id: 'rent' %> <button type="button" class="btn btn-success btn-lg" data-toggle="modal" data-target="#savingsModal"> See how quickly you can buy a home </button> </div>
总结
你的原始代码语法是正确的,能正常运行,但可以通过去掉冗余的后端交互属性让代码更清晰、更贴合你的需求。上面的优化版本都能完美支持你在模态框里执行JavaScript计算的功能。
内容的提问来源于stack exchange,提问作者SupremeA
相关产品推荐
相关产品推荐

