Spechal
Spechal

Reputation: 2716

How do I convert an ActiveRecord result array to a normal array?

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]

<% @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!

Upvotes: 23

Views: 29111

Answers (4)

hongxingshi
hongxingshi

Reputation: 61

You could also use:

@result.pluck(:ingredient_id)

Upvotes: 6

vvohra87
vvohra87

Reputation: 5674

If you are using a recent version of ruby, there is new way to do this:

@result.map(&:ingredient_id)

Time saver, clean and easy to interpret.

Upvotes: 25

Lucas Wiman
Lucas Wiman

Reputation: 11317

Or more succinctly @result.map! &:ingredient_id

Upvotes: 6

nonopolarity
nonopolarity

Reputation: 151234

you can use

@result.map {|i| i.ingredient_id }

Upvotes: 34

Related Questions