我正在尝试从视图内的另一个模型调用值。
tse.headoffice.head_office_id
在headoffice.rb中将关系定义为
has_many :tse
,在tse.rb中为
belongs_to :headoffice
现在,我收到未定义方法的错误
nil:NilClass的未定义方法“ head_office_id”
答案 0 :(得分:0)
<% if tse.headoffice.present? %>
<%= tse.headoffice.head_office_id %>
<% end %>
答案 1 :(得分:0)
try()
使您可以在对象上调用方法,而不必担心该对象为nil
并因此引发异常的可能性
<%= tse.try(:headoffice).try(:head_office_id) %>
答案 2 :(得分:0)
假设HeadOffice模型具有名为head_office_id
的属性:
<%= tse.headoffice.head_office_id if tse.headoffice %>
如果不是这种情况:
<%= tse.headoffice_id %>
答案 3 :(得分:0)
与此有关的事情看起来不正确。通常import numpy as np
n = 1000
I = np.random.randn(n,n)
I_min = np.min(I)
I = I + np.abs(I_min)
I_max = np.max(I)
I = 255 * (I / I_max)
I = I.astype(np.uint8)
引用是复数。您的命名方案可能与Rails自以为是的魔术混为一谈。
为什么has_many
会有一个名为headoffice
的字段?它是否只有一个名为headoffice_id
的字段?最后,一个nitpick,应该称为id
,而不是head_office
。 headoffice
也不是一个好名字。什么是tse
?如果可以,请拼写出来,并以单数或复数形式形成它。如果遵循这些简单的命名准则,Rails的效果会更好。
https://gist.github.com/iangreenleaf/b206d09c587e8fc6399e
请参见下面的简单示例:
post.rb
tse
comment.rb
has_many :comments
要访问帖子的评论,请输入以下内容:
belongs_to :post
或者,如果您不确定帖子中有评论,您会说:
Post.first.comment.body