浏览器和控制台之间的Active Record差异

时间:2015-09-18 07:11:53

标签: ruby-on-rails activerecord

我有一个典型的模型设置,其Parent模型有很多ImagesImage belongs_to Parent

Image有一个caption列。

我有一个视图,我通过Parent模型为每个循环执行标准,我想像这样拉出一个随机Image

<% @parent.each.with_index do |nut, index| %>
<h4><%= parent.name %></h4>
<p><%= parent.images.limit(1).order("RANDOM()").first.caption %></p>
<% end %>

在控制台中它可以正常工作。在视图中,它会抛出undefined method "caption" for nil:NilClass

首先我将其添加到Parent模型中:

  def random_caption

    self.images.limit(1).order("RANDOM()").first

  end

并使用:

<%= parent.random_caption.caption %>

甚至:

<%= parent.images.first.caption %>

这会导致同样的错误。我想我错过了Active Record的一些奇怪的细微差别或者不太明显的东西。

修改

也很奇怪 - 改为:

<%= parent.images.first %>

并且在视图中我得到了#<Image:0x007fd8f7404430>,所以看起来那里有一条记录。

2 个答案:

答案 0 :(得分:2)

必须有一些父记录没有任何图像。这就是你得到错误的原因。 在parent.images.limit(1).order("RANDOM()")您有记录之前,下面的行不会给出任何错误。它将返回对象数组或[]。因此,最好在此随机之前检查空白图像的条件。

parent.images.limit(1).order("RANDOM()").first.caption

因此,请尝试更改您的代码:

<% @parent.each.with_index do |parent, index| %>
  <h4><%= parent.name %></h4>
  <% if parent.images.present? %>
    <p><%= parent.images.limit(1).order("RANDOM()").first.caption %></p>
  <% else%>
    <p>No image there</p>
  <%end %>
<% end %>

答案 1 :(得分:0)

在您的数据库中,您有该父母的任何图像吗?

相关问题