Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an indexed hash as a result from activerecord

Tags:

Is there a way to pull records from activerecord in a hash already indexed by id instead of an array? This is what im currently doing:

results = {} Table.select { |current| results[current.id] = current } 

Im assuming that there has to be a method that does that?

like image 322
Leon Fedotov Avatar asked Dec 05 '12 22:12

Leon Fedotov


People also ask

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module...

What is ActiveRecord naming convention?

ActiveRecord expects applications to follow certain naming conventions. These conventions extend from file naming, class naming, table naming and more. By default classes are singular, tables are plural, primary keys are id and foreign keys are table_id.

What are ActiveRecord methods?

The active record pattern is an approach to accessing data in a database. A database table or view is wrapped into a class. Thus, an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save.

Is ActiveRecord part of rails?

Rails Active Records provide an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.


1 Answers

Table.all.index_by { |t| t.id } 

Or:

Table.all.index_by(&:id) 

if you're into the whole brevity thing.

like image 179
Jim Stewart Avatar answered Nov 05 '22 15:11

Jim Stewart