“未定义的方法‘名称’”对于 nil:NilClass”创建新实例时
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个简单的修复:
A simple fix:
如果没有最后状态或最后状态没有名称,请注意这一点
This should take care if there is no last status or the last status doesn't have name