ruby-on-rails - Array.shift 的问题

标签 ruby-on-rails ruby ruby-on-rails-3

我正在从我的 Controller 传递两个实例变量 @events = Event.all@images = Images.all。在 View 中,我首先遍历 @events.each do |event| 并且在这个 block 中是行 img = @images.shift 但是当我尝试访问任何img 的方法,例如 img.filename 我得到一个错误,imgnil 但我已经检查过确定 @images 已正确填充。如果我只是输出 img.class,我会收到正确的类 Image,但无法访问它的任何方法。

我做错了什么或者为什么这种从数组中提取实例的方法不正确?

我知道还有其他方法可以解决这个问题,但这个具体问题让我感到困惑,我真的很想了解为什么这不起作用。谢谢。

#Structure of the model is
Image
-filename :string
-date     :datetime
-caption  :text
-source   :string

#Controller
def index
  @events = Event.all
  @images = Image.all
end

#index.html.erb
<% @events.each do |event| %>
  ... code that works ...

  <% if count==1%>
    <% img = @images.shift %>
    <div><%= img.filename %></div>
  <% end %>

<% end %>

#For testing purposes I changed
<% img = @images.shift %>
<div><%= img.class %></div>

#output is Image

最佳答案

当事件多于图像时,可能会出现此问题。因为每次迭代通过 @events 数组时,@images 都会移动并从数组中获取下一个元素。因此,当您在 @events 中有例如 4 个元素而在 @images 中只有 3 个元素时,那么在第 4 次迭代时,会从 @images 中获取第 4 个元素,这是 nil

关于ruby-on-rails - Array.shift 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6107342/

相关文章:

ruby-on-rails - 如何替换 Ruby 中带重音的拉丁字符?

ruby - 数组乘法 - 什么是最好的算法?

ruby-on-rails - 带有 Rails grouped_collection_select 的 jQuery Selectmenu

ruby-on-rails - Elasticsearch 的多方面过滤器

ruby-on-rails - 通过引用更新属性

ruby-on-rails - 与 jail 长记住_我

ruby-on-rails - 如果出现验证错误,如何自定义 respond_with 呈现的 JSON?

ruby-on-rails - 模拟 XHR GET 请求

ruby - 用于从频率生成WAV文件的Ruby API?

ruby - ruby 中的类方法和不同的编程风格