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

时间:2015-01-14 01:57:38

标签: ruby-on-rails ruby

我不断遇到错误,因为它不存在而无法链接到对象。通常,对象,比如“商店”有一个“顾客”,所以在商店展示页面上,我想链接到那里购买的顾客(通过“促销”模式)。

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

上收到no方法错误

我应该做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)。

1 个答案:

答案 0 :(得分:4)

为与此类似的案件创建了

link_to_if

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