DEV Community

Joe Lee
Joe Lee

Posted on

Rails Basic Flow

Workflow for basic Ruby on Rails app:

A. Establish model relations and associations

B. Create models, migrations, associations, validations

rails g model Cheese name price:integer
Enter fullscreen mode Exit fullscreen mode

this command will also make the create_cheeses migration table
name is defaulted as a string

belongs_to :cheese
has_many :stores, through: :cheeses, dependent: :destroy
validates :name, presence: true, uniqueness: true
Enter fullscreen mode Exit fullscreen mode

syntax for associations and validations, both are done in the model.rb files

then run

rails db:migrate db:seed
Enter fullscreen mode Exit fullscreen mode

There's also db:seed:replant to refresh your database seeds

C. Routes

resources :cheeses, only: [:index, :show, :create, :update, :destroy]
Enter fullscreen mode Exit fullscreen mode

syntax for using resource routes and only with the conventional names for the 5 CRUD functions. Note that only wouldn't technically be used here because it's including all of them.

D. CRUD

Now write the 5 CRUD functions:.
:index and :create don't need ID, all other 3 will need syntax like this:

Cheese.find(params[:id])
Enter fullscreen mode Exit fullscreen mode

.find will throw ActiveRecord::RecordNotFound, and using create! and update! will throw ActiveRecord::RecordInvalid, so we can rescue from those throws like this:

rescue_from ActiveRecord::RecordNotFound, with: :render_not_found_response
Enter fullscreen mode Exit fullscreen mode

the :render_not_found_response function should be in the private section of the model, along with a wrapper for the 'find-by-id' code, as well as strong params:

params.permit(:name, :price)
Enter fullscreen mode Exit fullscreen mode

which I will be using for :create and :update functions to make sure I get the proper data for the object.

remember to use these statuses:

status: :created, :not_found, :unprocessable_entity
Enter fullscreen mode Exit fullscreen mode

Top comments (0)