Ruby on rails nil:NilClass的未定义方法“image\u file\u name”
我正在努力找出为什么我不能让这个助手正常工作。Item类具有对产品类的嵌套引用。如何在下面的帮助器功能中正确访问产品属性Ruby on rails nil:NilClass的未定义方法“image\u file\u name”,ruby-on-rails,Ruby On Rails,我正在努力找出为什么我不能让这个助手正常工作。Item类具有对产品类的嵌套引用。如何在下面的帮助器功能中正确访问产品属性 module ItemHelper def image_for(item) if item.product.image_file_name.blank? image_tag('placeholder.png') else image_tag(item.product.image_file_name) end end end 我得到以
module ItemHelper
def image_for(item)
if item.product.image_file_name.blank?
image_tag('placeholder.png')
else
image_tag(item.product.image_file_name)
end
end
end
我得到以下错误。
nil:NilClass的未定义方法“image\u file\u name”
它发生在访问另一个html文件中的函数时。我认为这是因为我在无法访问item.product的地方做错了什么
下面的代码实际上是运行代码,表明我已经在数据库和模型中设置了我认为正确的关系
<ul id="items">
<% @items.each do |item| %>
<li>
<article class="item">
<header>
<h2><%= item.product.name %></h2>
</header>
<p>
<%= truncate(item.description, length: 150, separator: ' ') %>
</p>
<table>
<tr>
<th>Price</th>
<td><%= item.product.price %></td>
</tr>
</table>
<footer>
</footer>
</article>
</li>
<% end %>
</ul>
下面是我用来调用helper函数的代码
<article id="hint" class="hint">
<header>
<%= image_for(@hint) %>
<h1><%= @hint.name %></h1>
</header>
<p>
<%= @hint.description %>
</p>
<footer>
</footer>
</article>
有人有什么建议吗?试试下面的代码:
def image_for(item)
if item.product.nil? || item.product.image_file_name.blank?
image_tag('placeholder.png')
else
image_tag(item.product.image_file_name)
end
end
>我无法访问item.product。你说得对。产品似乎返回零。您确定已正确设置数据库和模型中产品和项目之间的关系吗?感谢回复Dylan。我相信这个设置是正确的,因为我可以在index.html.erb中引用产品对象。我在原文中添加了上面的代码,所以你可以看到。然而,你肯定有一个没有产品的项目。这是基于您发布的代码,该错误可能以单一方式发生。您无意中调用了nil.image\u file\u name,如果这些是调用image\u file\u name的唯一位置,那么其中一行的item.product为nil。我在上面添加了调用helper方法的代码。也许这会有帮助。要从视图中的控制器访问变量,它们必须是实例变量,并且必须以@开头。