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
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
syntax for associations and validations, both are done in the model.rb files
then run
rails db:migrate db:seed
There's also db:seed:replant to refresh your database seeds
C. Routes
resources :cheeses, only: [:index, :show, :create, :update, :destroy]
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])
.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
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)
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
Top comments (0)