为什么在 Rails 中,belongs_to 关系的结果为零?
我的 Ruby on Rails 应用程序中遇到一个问题,其模型中的 own_to 关系始终为零。
给定以下模型:
class Chassis < ActiveRecord::Base
belongs_to :model
belongs_to :chassis_size
end
class Model < ActiveRecord::Base
has_many :chassis
end
class ChassisSize < ActiveRecord::Base
has_many :chassis
end
现在,我希望在我的底盘索引视图中,我会看到给定的模型和底盘尺寸数据:
<% @chassis.each do |chassis| %>
<%= chassis.id %><br />
<%= chassis.model.name %><br />
<%= chassis.chassis_size.size %><br />
<% end %>
但我收到一个错误,底盘尺寸.尺寸为零:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.size
查看数据库中的数据,一切都出现是正确的。
我不知道为什么 model 可以工作,但chassis_size 却不能。我缺少什么?为什么chassis_size数据似乎没有加载?
I'm having a problem in my Ruby on Rails app with a model where a belongs_to relationship keeps ending up being nil.
Given the following models:
class Chassis < ActiveRecord::Base
belongs_to :model
belongs_to :chassis_size
end
class Model < ActiveRecord::Base
has_many :chassis
end
class ChassisSize < ActiveRecord::Base
has_many :chassis
end
Now, I would expect in my chassis index view I would see both the model and the chassis_size data given:
<% @chassis.each do |chassis| %>
<%= chassis.id %><br />
<%= chassis.model.name %><br />
<%= chassis.chassis_size.size %><br />
<% end %>
But I get an error that the chassis_size.size is nil:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.size
Looking at the data in the database, everything appears to be correct.
I am not sure why model works but chassis_size does not. What am I missing? Why doesn't the chassis_size data appear to load?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尺寸是您的chassis_sizes 表中的一列吗?
如果是这样,那么这是 ruby 中的保留字,因为它是返回数组长度的方法。
每个机箱都有一个chassis_size吗?试试这个:
Is size a column in your chassis_sizes table?
If so, this is a reserved word in ruby, as it is the method for returning the length of an array.
Does every chassis have a chassis_size? Try this: