如果关联对象为 nil,则 Rails link_to



>我不断收到错误,无法link_to对象,因为它不存在。通常对象,比如"商店"有一个"客户",所以在商店显示页面上,我想链接到在那里购买的客户(通过"销售"模型)。

无论出于何种原因,客户不再在数据库中,因此当我执行link_to warehouse.customer_id customer_path(warehouse)时,我收到 nil 或 No route matches {:action=>"show", :controller=>"customers", :id=>nil} missing required keys: [:id] 的无方法错误

我应该做link_to warehouse.customer_id customer_path(warehouse) if warehouse.customer.present?还是在它周围放一个 if 语句,以便我可以显示customer_id而不是什么都没有

<% if @contract.customer.present? %>
  <p><%= link_to @contract.customer_id, customer_path(@contract.customer) %>
<% else %>
  <p><%= @contract.customer_id %>
<% end %>

第二个选项看起来很混乱,会弄乱我的视图,但如果对象不存在,我不想不显示信息:/

我还有一个路由异常处理程序,如果数据库中不存在该对象,则可以重定向到root_url,但这意味着制作我的link_to customer_path(warehouse.customer_id)而不仅仅是customer_path(warehouse.customer)。

link_to_if是为

类似的情况创建的。

link_to_if @contract.customer, @contract.customer_id, @contract.customer

最新更新