[Rails] Active Record method that even beginners often use

What is Active Record

A function of Ruby on Rails that allows you to handle database data without writing SQL. This is sometimes called ʻOR mapper. With Active Record, you can handle data with simple methods without writing SQL statements.

By the way, regardless of Rails, the PHP framework also uses this OR mapper.

User.all

users = User.all

Get information for all users.

User.find

user = User.find(1)

Get the record of the user whose primary key matches.

User.find_by

user = User.find_by(name: 'gorira')

Get the first record that the data in the column matches under the specified conditions.

User.first

user = User.first

Get the first record of the user.

User.where

user = User.where(name: 'takeshi')

Get all records that match the conditions.

User.pluck

users_name = User.pluck(:name)

Get a specific column as an array.

User.order

user = User.order('id DESC')

Sorts based on the specified column.

User.delete_all

user = User.delete_all

Delete all data in the user table.

User.eager_load

user = User.eager_load(:items)

Outer join and get all the data.

Reference article

https://railsguides.jp/active_record_basics.html

Recommended Posts

[Rails] Active Record method that even beginners often use
What is Rails Active Record?
[Rails] How to use Active Storage
[Rails] How to use the map method
[Ruby on Rails] About Active Record callbacks
[Rails] How to use helper method, confimartion
rails method
Read the Rails Guide (Active Record Migration) again
[Ruby on Rails] How to use session method