Ruby-on-rails 如何将 ActiveRecord 结果数组转换为普通数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4241211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert an ActiveRecord result array to a normal array?
提问by Spechal
How do I convert the resultset of @recipe.components.find ( [# <Component ingredient_id: 1>, # <Component> ingredient_id: 2>] ) to an array such as [1,2]
如何将@recipe.components.find ( [# <Component composition_id: 1>, # <Component>成分_id: 2>] ) 的结果集转换为数组,例如 [1,2]
<% @ingredients.each do |ingredient| %>
<div class="field">
<%= check_box_tag 'ingredients[]', ingredient.id, @recipe.components.find(:all, :select => "ingredient_id").include?(ingredient.id) %><%= ingredient.name %>
</div>
<% end %>
Thanks!
谢谢!
回答by nonopolarity
you can use
您可以使用
@result.map {|i| i.ingredient_id }
回答by vvohra87
If you are using a recent version of ruby, there is new way to do this:
如果您使用的是最新版本的 ruby,有一种新方法可以做到这一点:
@result.map(&:ingredient_id)
Time saver, clean and easy to interpret.
节省时间,干净且易于解释。
回答by hongxingshi
You could also use:
您还可以使用:
@result.pluck(:ingredient_id)
回答by RecursivelyIronic
Or more succinctly @result.map! &:ingredient_id
或者更简洁 @result.map! &:ingredient_id

