繁体   English   中英

Ruby on Rails 阵列访问

[英]Ruby on Rails Array access

我的问题涉及一个显然不是 nil 的数组,但是当我尝试访问它时,它是。

该数组是从对活动记录的查找中返回的。 我已经确认它实际上是一个带有 .class 方法的数组

@show_times = Showing.find_showtimes(params[:id])
@show_times.inspect =>shows that the array is not empty and is a multidimensional array.
@show_times[0] =>is nil
@show_times[1] =>is nil
@show_times.first.inspect => NoMethodError (undefined method `first')

我很困惑为什么会这样。。

它不是一个数组,它是一个活跃的记录魔术结构,大部分看起来像一个数组。 我认为您可以对其执行 to_a 以获得真正的数组,但随后很多魔法就消失了。

find_showtimes不是内置查找器 - 如果是,它将返回单个 ActiveRecord object 或 ActiveRecord 对象数组 - 绝不是多维数组。 所以我要做的第一件事就是看看那个方法的来源。

编辑:给定您的源代码(在评论中)-您实际上从您的取景器中得到了一个 Hash,而不是一个数组。 请参阅Enumerable 的 group_by 的文档 Hash 将您的剧院对象映射到放映对象数组。 这就是你想要做的:

Showing.find_showtimes(params[:id]).each do |theater, showtimes|
  puts "Theater #{theater} is showing the movie at #{showtimes.join(', ')}"
end

如果您在控制台中并且想探索@show_times object,您可以使用keys方法查看所有hash键,然后获取单个Z0800FC577294C34E0B28AD283943595等项目(所有显示时间)如:

@show_times[:theater_one]

同样的事情将在您的模型/视图中工作,但使用 each/map/collect 会更干净,因为漂亮的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM