Ruby 由返回的集合。其中未按预期响应
我试图通过where查询定义一个新数组,但我只能以一种方式让它工作 这是:Ruby 由返回的集合。其中未按预期响应,ruby,ruby-on-rails-3,activerecord,where,Ruby,Ruby On Rails 3,Activerecord,Where,我试图通过where查询定义一个新数组,但我只能以一种方式让它工作 这是: <% @children = Array.new Topic.where(breadcrumb_id: @topic.id).each do |y| @children.push(y.name) end return @children %> Returns the array ["Performance Arts", "Visual Arts", "Physical A
<%
@children = Array.new
Topic.where(breadcrumb_id: @topic.id).each do |y|
@children.push(y.name)
end
return @children
%>
Returns the array ["Performance Arts", "Visual Arts", "Physical Arts", "Music", "Culinary Arts"] (All topics)
但我更愿意这样做
@children = Topic.where(breadcrumb_id: @topic.id)
return @children.each.name
Returns "undefined method `name' for #<Enumerator:0x007fe92205a1f0>"
不管是什么原因,每个人都不会正确回答。。。尽管它在第一个示例中的初始where调用上有效。有什么区别
有没有一种方法可以直接从数组中提取名称 where方法返回一个对象,而不是数组 要获取数组,请调用all或对其执行以下操作:
@children = Topic.where(breadcrumb_id: @topic.id).all
@children = Topic.where(breadcrumb_id: @topic.id).to_a
请注意,您不需要将其转换为数组来对其进行迭代
查看Frederick Cheung关于为什么使用每个方法都不起作用的答案。where方法返回一个对象,而不是数组 要获取数组,请调用all或对其执行以下操作:
@children = Topic.where(breadcrumb_id: @topic.id).all
@children = Topic.where(breadcrumb_id: @topic.id).to_a
请注意,您不需要将其转换为数组来对其进行迭代
看看张弗雷德里克的答案,为什么你使用每一个都不起作用。这不是每一个都起作用。您可能正在查找地图或其别名collect
您可以使用Symbolto_proc快捷方式将其缩短一点:
Topic.where(...).map &:name
这不是每个人都做的。您可能正在查找地图或其别名collect
您可以使用Symbolto_proc快捷方式将其缩短一点:
Topic.where(...).map &:name
在Rails 3.2中,还有Pulk:
这还有一个额外的好处,就是从。。。除了在Rails 3.2上选择*之外,还有以下功能:
这还有一个额外的好处,就是从。。。而不是选择*多谢各位。我被困在这个问题上大约2个小时。你不能打电话给Topic.wherebreadcrumb_id:@Topic.id.to_a.name,这里的ActiveRecord::Relation没有问题。谢谢大家。我被困在这个问题上大约2个小时。你不能调用Topic.wherebreadcrumb_id:@Topic.id.to_a.name,这里的ActiveRecord::Relation没有问题。我对这两个方面都不太熟悉。我得测试一下,然后仔细阅读。这两种我都不太熟悉。我得测试一下,然后仔细阅读。我已经忘记了勇气!它看起来实际上并没有实例化任何活动记录对象,所以应该比主题稍微快一点。选择'name'!它看起来实际上并没有实例化任何活动记录对象,所以应该比主题稍微快一点