We want to create a dog directory with basic CRUD functionality. The pieces we will need to make it all work are:
- Dogs Routes
- Dogs Controller
- Dogs Views
- Dog Model
If we want access to the full CRUD suite we can use the resources method in our routes file config/routes.rb
resources :dogs
If we want to not be allowed to delete dogs we can pass additional arguments:
resources :dogs, except: [:destroy]
Note that even if except (or only) use just a single action it still needs to be in an array
If we want to see what our routes look like, we can run the rails routes
command in the terminal at any time.
We can use the generator to create a controller:
rails generate controller Dogs
This generates a bunch of files including the important controller file:
app/controllers/dogs_controller.rb
We will put our action methods in here. E.g.,
class DogsController < ApplicationController
def index
end
def show
@dog = Dog.find(params[:id])
end
# ...and so on
end
Views are easy to set up. The controller generator should have already set up the folder for these views. It's just a matter of make a new file for each action:
app/views/dogs/index.html.erb
app/views/dogs/show.html.erb
app/views/dogs/new.html.erb
These views have access to our instance variables defined in our controller actions. E.g., in app/views/dogs/show.html.erb
we can put:
<h1><%= @dog.name %></h1>
<p>Dog Breed: <%= @dog.breed %></p>
If we know what columns our dogs table needs, it's easy to set up the Model using the rails generator.
rails g model name:string breed:string housebroken:boolean
This creates the model file for us, which is the bridge between us and the database. Note: the model class is always singular.
app/models/dog.rb
This is where we get the methods from to interact with the database.
Dog.create(name: "Fido", breed: "Pug", housebroken: true)
Dog.find(1)
Dog.all
We first should make a new dog in the command line:
rails console
Then simply use the Model to make a new dog object which will save to the database.
Dog.create(name: "Fido", breed: "Pug", housebroken: true)
Now we can run our server, rails server
, and check our dogs routes. Let's check the one we set up for showing a single dog.
http://localhost:3000/dogs/1
This hits the router with a GET request to /dogs/:id, forwards the request to the DogsController's show action. The show action by default renders the views/dogs/show.html.erb file, returns some HTML and then the server sends that back to our browser.
That's it, we have built a super basic rails app in no time!
resources :dogs, expect: [:destroy]
is it "expect" or "except"
?