“未定义的方法‘名称’”对于 nil:NilClass”创建新实例时

发布于 2024-10-03 10:19:37 字数 769 浏览 0 评论 0原文

我在 Rails 中遇到了一个问题,两个模型(顺序和状态)之间存在基本的多对多关系。这些模型如下所示:

class Order < ActiveRecord::Base
  has_many :products, :through => :lines
  has_and_belongs_to_many :statuses

  default_scope order("#{table_name}.created_at desc")
end

class Status < ActiveRecord::Base
  has_and_belongs_to_many :orders

end

订单索引视图中,我显示订单的最新状态,因此 order.statuses.last.name,但是,当我创建新订单时,我收到错误。此错误是由于未定义的方法名称造成的,因为新订单在首次创建时没有任何关系。

我的问题是,在保存新订单之前,有没有办法初始化两个模型之间的关系?我希望我的订单至少始终在状态集合中具有第一个状态,但不希望在保存之前必须手动检查它。

好的措施的错误是:

undefined method `name' for nil:NilClass

对于我看来的这句话:

<td><%= order.statuses.last.name %></td>

谢谢大家。

I'm having an issue within rails where, I have a basic many to many relationship between two models (order and status). These models look like the following:

class Order < ActiveRecord::Base
  has_many :products, :through => :lines
  has_and_belongs_to_many :statuses

  default_scope order("#{table_name}.created_at desc")
end

and

class Status < ActiveRecord::Base
  has_and_belongs_to_many :orders

end

Within my index view for orders, I'm displaying the Order's most recent status, so order.statuses.last.name, however, when I create a new Order, I receive an error. This error is for an undefined method name, as the new orders are not having any relationship when they're first created.

My question is, is there a way to initialize a relationship between my two models, before saving a new order? I'd want my orders to always at least have the first status in my statuses collection, but don't want used to have to manually check it before saving.

The error for good measures is:

undefined method `name' for nil:NilClass

for this line in my view:

<td><%= order.statuses.last.name %></td>

Thanks all.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

故人爱我别走 2024-10-10 10:19:37

一个简单的修复:

<td><%= order.statuses.last.name if order.statuses %></td>

A simple fix:

<td><%= order.statuses.last.name if order.statuses %></td>
爱要勇敢去追 2024-10-10 10:19:37

如果没有最后状态或最后状态没有名称,请注意这一点

<td><%= order.statuses.last.try(:name) %></td>

This should take care if there is no last status or the last status doesn't have name

<td><%= order.statuses.last.try(:name) %></td>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文