23

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!

4 Answers 4

34

you can use

@result.map {|i| i.ingredient_id }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I needed @result.map! { |i| i.ingredient_id }
map is your friend. Also get to know the "ect" triplets: select, reject and inject.
25

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.

3 Comments

Looks like Ruby is gaining even more ability to be cryptic then.
@Spechal it's not to be cryptic! Simply put, the map method exposes the underlying enumeration interface for any array, hash, etc. The "&" is just short notation when you wish to send / trigger a single method on each object in the array. And in this case the :ingredient_id is the symbol representation of the method.
@Spechal Oh and I forgot to mention, if you are using Rails 3.2.x there is a simpler method! Just call MyModel.find(conditions).pluck(&:ingredient_id)... this is much faster since the pluck method is basically a single column select so you wont waste time in fetching all the data, presuming of course that you only want the values in a single column!
6

Or more succinctly @result.map! &:ingredient_id

Comments

6

You could also use:

@result.pluck(:ingredient_id)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.