A neccessary review
Source: Dev.to
In our first class I was behind the ball in the first 5 minutes. Even remembering how to start up my test server was a distant memory from App Dev I. Throughout the class the material started to look familiar as the rust began to fall off.
To aid in my review I’m documenting building out the directors model and sharing some learnings along the way.
Our goal
Develop a symmetrical functionality to the movies: model for directors using idiomatic (as far as I know) Ruby.
Key functions
- Display an index of directors that links to each director’s page
- Show each director’s details on their own page
- Allow edits to each director
- Delete a director entry
Model
Generate the model with:
rails g model Director name dob styleAdd validations:
class Director "directors#create", as: :directors
get "/directors/new" => "directors#new", as: :new_director
# READ
get "/directors" => "directors#index"
get "/directors/:id" => "directors#show", as: :director
# UPDATE
patch "/directors/:id" => "directors#update"
get "/directors/:id/edit" => "directors#edit", as: :edit_director
# DELETE
delete "/directors/:id" => "directors#destroy"Controller
class DirectorsController < ApplicationController
def new
@director = Director.new
end
def index
@directors = Director.all.order(:created_at, name: :desc)
respond_to do |format|
format.json { render json: @directors }
format.html
end
end
def show
@director = Director.find(params.fetch(:id))
end
def create
director_attributes = params.require(:director).permit(:name, :dob, :style)
@director = Director.new(director_attributes)
if @director.save
redirect_to director_url(@director), notice: "Director was successfully created."
else
render :new
end
end
def edit
@director = Director.find(params.fetch(:id))
end
def update
@director = Director.find(params.fetch(:id))
director_attributes = params.require(:director).permit(:name, :dob, :style)
if @director.update(director_attributes)
redirect_to director_url(@director), notice: "Director updated successfully."
else
render :edit
end
end
def destroy
director = Director.find(params.fetch(:id))
director.destroy
redirect_to directors_url, notice: "Director deleted successfully."
end
endActions
No additional custom actions are needed beyond the standard RESTful set.
Views
The views are similar to those for the movies resource, so they have been omitted here.
Conclusion
Everything now works as expected. Using idiomatic Ruby conventions makes development faster, even though it can be confusing at times.