Ruby on Rails中如何在ERB文件中根据ID存在性条件显示按钮
解决新建客户时按钮报错的问题
嘿,这个问题我之前也碰到过!核心原因很明确:新建客户时,@customer 是还没存进数据库的新实例,它的 id 是 nil,直接传给 customer_path 肯定会因为缺少必要参数报错;但编辑的时候实例已经有合法的 id 了,所以一切正常。
这里有几种简单靠谱的修复方式:
方法一:用 persisted? 判断实例是否已保存
persisted? 是Rails模型自带的方法,只有当实例已经保存到数据库(也就是有有效 id、不是新记录)时才会返回 true。我们用它把按钮代码包起来就行:
<% if @customer.persisted? %> <div class='pull-right'> <%= button_to 'Kundenrofil', customer_path(@customer), method: :get %> </div> <% end %>
方法二:用 new_record? 反向判断
和 persisted? 相反,new_record? 在实例是未保存的新状态时返回 true,所以也可以这么写:
<% unless @customer.new_record? %> <div class='pull-right'> <%= button_to 'Kundenrofil', customer_path(@customer), method: :get %> </div> <% end %>
小优化:简化路径写法
其实Rails里有个小技巧,当实例是已保存状态时,customer_path(@customer) 和直接写 @customer 是等价的,Rails会自动解析成正确的路径,所以代码还能更简洁:
<% if @customer.persisted? %> <div class='pull-right'> <%= button_to 'Kundenrofil', @customer, method: :get %> </div> <% end %>
这样既符合Rails的最佳实践,读起来也更清爽~
内容的提问来源于stack exchange,提问作者Ilja KO
相关产品推荐
相关产品推荐

