Bopes DB Cheatsheet

ActiveRecord (Ruby ORM)

Class Methods

These are chainable, but can only be called on a class or ActiveRecord_Relation (which are like arrays). So they can't be chained in just any order.

For instance, #count returns an integer and #pluck returns an array, so they should be the last methods called.


View All

Class.all

Returns ActiveRecord_Relation containing all instances of the class

Where

Class.where(column: search_value)

Returns ActiveRecord_Relation containing all instances meeting the criteria

Where (Multiple Criteria)

Class.where({column1: value1, column2: value2})

OR

Class.where("column1: ? AND column2: ?", value1, value2)

Returns ActiveRecord_Relation containing all instances meeting all the multiple criteria

Order

Class.order(column: :asc/:desc)

Returns an ordered ActiveRecord_Relation

Count

Class.count

Returns integer count of elements in class

Pluck

Class.pluck(:column1, :column2, etc.)

Returns an array of arrays containing these values for every instance of class

First

Class.first

Returns the first instance of the class

Find

Class.find(#id)

Returns the instance of the class with the given #id

Find By

Class.find_by(column: search_value)

Returns the first instance of the class that matches the search criteria

Creating Records

New

Class.new(column1: value1, column2: value2, etc.)

Instantiates a new instance of the class. This is not saved in the database. It will not have an #id until it's been saved, so don't give it one. Returns the new instance.

Persisted?

instance.persisted?

Returns boolean announcing if the instance has been persisted in the database.

Save

instance.save

Saves the instance to the database and assigns it an #id. Returns boolean if the instance saved sucessfully.

Create

Class.create(column1: value1, column2: value2, etc.)

Instantiates and saves the new instance simultaneously. Returns the new instance.

Create Multiple

Class.create [{column1: value1}, {column1: value2}]

Creates multiple instances at once. Returns an array of the new instances.

Find or Initialize By

Class.find_or_initialize_by(column: value)

Looks for the criteria in the database. If not found, it creates a new instance. Returns the found or initialized instance. Does not save the initialized instance.

Find or Create By

Class.find_or_create_by(column: value)

Looks for the criteria in the database. If not found, it creates a new instance. Returns the found or initialized instance. New instances are saved directly to the database.