2023-05-23 - Rails Models


main topics


7 routes/actions for a typical CRUD

route action
get '/tasks' index
get '/tasks/:id' show
get '/tasks/new' new
post '/tasks' create
get '/tasks/:id/edit' edit
patch '/tasks/:id' update
delete '/tasks/:id' destroy

Bricks of a WebApp

main steps

rails new tasks
cd tasks

rails generate model task title:string details:text

# check the migrations
# - add configs (defaults/validations) if needed
# check models
# - add validations or custom methods if needed

rails db:migrate

# play with the model in the console
rails console --sandbox

# create the controller
rails generate controller tasks \
  index show \
  new create \
  edit update \
  destroy
# the files still need to be edited!
# router -> controller -> view

Route

Replace the routes with resources :tasks.

Controller

# class Controller...
before_action :set_task, except: %i[index new create]

# ...
# 7 CRUD methods go here...

private

def set_task
  @task = Task.find(params[:id])
end

def task_params
  params
    .require(:task)
    .permit(:title, :details, :completed)
end
# end of the class

View

next?

From here, check: