【问题标题】:Why can't i access enum method through association?为什么我不能通过关联访问枚举方法?
【发布时间】:2020-09-06 05:26:19
【问题描述】:

我对 RoR 有点陌生,但我遇到了一个愚蠢的问题(我认为)。我有两个模型 - 产品和订单。 Order belongs_to product 和 Product has_one order。

在我的订单模型中,我有以下枚举:enum situation: { in_progress: 0, finished: 10 }

在我的控制器中(我得到了登录用户注册的产品集合)

@user = current_user
@products = @user.products

然后,在我看来,我正在通过@products 进行交互,我想检查特定产品的订单状态:

> <% @products.each do |product| %>
>     <% if product.order.in_progress? %>
>        do x
>     <% else %>
>        do y
>     <% end %> 
> <% end %>

但我不断得到:

未定义的方法`in_progress?'对于 nil:NilClass

我无法通过产品关联访问订单?

【问题讨论】:

  • 感谢@spickermann 的回答。即使我使用 has_one 关联?
  • @hawkrox 当你使用 has_one 关联时,你应该使用单数。大多数问题可以从 ROR 指南中找到答案。guides.rubyonrails.org/association_basics.html

标签: ruby-on-rails ruby enums associations


【解决方案1】:

当 t 行 product.order.in_progress? 引发 undefined method 'in_progress?' for nil:NilClass 时,这意味着 product.order 必须返回 nil。您的数据库中至少有一个 product 还没有订单,您需要在视图中处理它。

我会从这样的开始:

<% @products.each do |product| %>
  <% if product.order.blank? %>
     # no order yet
  <% elsif product.order.in_progress? %>
     do x
  <% else %>
     do y
  <% end %> 
<% end %>

顺便说一句product has_one order真的有道理吗,每个产品只能带一次吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多