rails console Frequently used operations

Introduction

Since I started learning rails and used the rails console more often, I will summarize it here.

operation

Start-up

rails c

End

quit

Get all data

As an example, the model name is ʻUser`.

User.all

Search by id

users = User.all
users.find(1)

Search by specifying id

users = User.all
users.find_by(id:1)  # users.find(1)Same meaning as

When searching by user name As an example, the column name is ʻusername`.

users.find_by(username:'Naoki')

save

user.save

Specific example: Rewriting the name

user = User.find(1)
user.username = 'Baikinman'
user.save

Delete

user.destroy

Specific example: Delete record

user = User.find(1)
user.destroy

reference

[Introduction to Rails] Summary of how to use console Manipulate Model in Rails Console

Finally

After adding data to the database with the app, basically it seems that there is no problem if you remember this operation method. We look forward to helping you.

Recommended Posts

rails console Frequently used operations
Various rails migration operations
Frequently used docker-compose command
Frequently used Java generics
Summary of frequently used commands in Rails and Docker
Gem often used in Rails
Frequently used processes in SpreadSheet
Frequently used Maven command collection
git flow Frequently used commands Memo
Frequently used methods in Active Record
Summary of frequently used Docker commands
Commands often used in MySQL operations
[Docker] Other frequently used (probably) Docker Instructions
Ruby methods often used in Rails
Introduction to Docker (1) Frequently used commands