Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 795
Spechal Avatar asked Nov 22 '10 00:11

Spechal


People also ask

What does ActiveRecord base mean?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is an ActiveRecord relation object?

The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.

What is Ruby ActiveRecord?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.


2 Answers

you can use

@result.map {|i| i.ingredient_id } 
like image 87
nonopolarity Avatar answered Oct 08 '22 11:10

nonopolarity


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.

like image 24
vvohra87 Avatar answered Oct 08 '22 10:10

vvohra87