Let’s Build: TaskBot (A Simple CRUD App using Ruby on Rails) — Part 1
Welcome to Let’s Build — a series dedicated to building projects to improve your skills as a Ruby on Rails developer!
Enter, TaskBot!
For the first part of the project, we’ll be creating a barebones, simple application— just one single model (Robots!!) with full CRUD functionality!
First things first, let’s create a brand-new rails app in your current directory!
Open up your Terminal (personally, I use iTerm2) and enter the following command:
rails new task-bot-app -T
Change into the task-bot-app folder:
cd task-bot-app
Let’s use a handy rails generator to make our Robot model, Robots Controller, Robot Routes and the migration file for our SQLite Database.
— I, ROBOT. SURRENDER ALL RESOURCES. *beep boop*
rails generate resource robot name:string slogan:string
and this is what should happen after you enter that command:
Running via Spring preloader in process 23552
invoke active_record
create db/migrate/20190122162556_create_robots.rb
create app/models/robot.rb
invoke controller
create app/controllers/robots_controller.rb
invoke erb
create app/views/robots
invoke helper
create app/helpers/robots_helper.rb
invoke assets
invoke coffee
create app/assets/javascripts/robots.coffee
invoke scss
create app/assets/stylesheets/robots.scss
invoke resource_route
route resources :robots
As you can see, this created all the files we needed to start (plus some files for Testing but we won’t be using those for this tutorial)!
Four big starting pieces in one command! Robot takeover imminent.
You can always just create the files individually by hand, but you’ll find the process gets very repetitive as you create more Rails applications! However, feel free to build them out yourself if you’re looking for the most hands-on learning experience in building a Rails app.
Rake it up, Rake it up. Back it up, Back it up.
So, we created a migration file for our Robots table in our database that’ll have a :name and a :slogan. Robot’s have catch-phrases, I guess.
Let’s migrate our changes to our database so Robots can actually exist and begin their rise to glory!
In your Terminal, let’s type in the following Rake command!
rake db:migrate
Now, check the schema file to double-check that it all worked!
Awesome, we now have our Robots database table that’ll house all our Robots for them to do their beeps and boops all in one place. Gotta keep track of them all!
You’ll notice that when you use the Resource command that even though we only entered the:name and :slogan columns, we actually got two bonus columns of :created_at and :updated_at! These may or may not be handy for you but hey, I like the extra functionality!
Bye, Pallet Town. Hello, Route 5.
Let’s check our Rails Routes by typing this into our Terminal:
rails routes
You’ll see the following come up on-screen. It’s a list of all the Routes that is handled by the ‘resources’ part in our config/routes.rb file. We can use these to create Route Helpers which we’ll use as we continue to build our app.
To give you the gist, we can type in robots_path
in our code and Ruby would read that and almost magically know we want to see a list of our Robots in our Index page (see the first line under the column headers, under prefix. We take that word, in this case robots
and add the _path
part to the end and we now have a Route Helper! Boo yah!
Why on Earth are we helping Robots takeover is not the concern right now.
.. Let’s just do it to see if we can.
Johnny Appleseed, Meet SEED-3PO.
Now, let’s add some fresh Seeds!
The seed.rb file is found in your ‘db’ folder which stands for database.
Seeds are meant for us to create objects in our database with their accompanying key/value pairs of data such as their :name and :slogan.
So, for our project, I made a few minion-bots to start the revolution.
Great! Now, let’s rake ’em in! Use this command to seed the database with our newly made robots.
rake db:seed
Check the Rails Console with your Terminal by typing in:
rails console
After pressing ‘enter’ to enter the console, type in:
Robot.all
and you should get something like this:
2.3.3 :001 > Robot.all
Robot Load (0.9ms) SELECT "robots".* FROM "robots" LIMIT ? [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Robot id: 1, name: "Gigabit", slogan: "Only my army of killer robots understands me..", created_at: "2019-01-22 17:05:13", updated_at: "2019-01-22 17:05:13">, #<Robot id: 2, name: "Rob Bitt", slogan: "I am not a simple Computer.", created_at: "2019-01-22 17:05:13", updated_at: "2019-01-22 17:05:13">, #<Robot id: 3, name: "Screwie", slogan: "I'm still in beta..", created_at: "2019-01-22 17:05:13", updated_at: "2019-01-22 17:05:13">, #<Robot id: 4, name: "Brobot", slogan: "Optimus Primates RULE!", created_at: "2019-01-22 17:05:13", updated_at: "2019-01-22 17:05:13">, #<Robot id: 5, name: "Databorg", slogan: "I am borg.", created_at: "2019-01-22 17:05:13", updated_at: "2019-01-22 17:05:13">]>
2.3.3 :002 >
Excellent! The Robot Army has been seeded!
Type ‘exit’ to exit out of the Rails Console.
2.3.3 :002 > exit
Am I your Server, or am I your Master?
Now, let’s get a Server up and running. Open up a new Terminal window/tab, and get back into (aka cd into) the task-bot-app directory. Then, type:
rails server
and then you’ll see:
➜ task-bot-app git:(master) ✗ rails server
=> Booting Puma
=> Rails 5.2.2 application starting in development
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.12.0 (ruby 2.3.3-p222), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop
Leave this Terminal window/tab on by itself as we use the original Terminal window/tab to continue working.
So now, if you go into your web browser, type in the URL box:
http://localhost:3000/
..and you’ll be congratulated by Rails!
Woo! Robots on Rails!
So, now that everything is up-and-running, let’s build out our Robots Controller and the corresponding Views before these bots get out of hand!
Open up your RobotsController.rb file in the ‘app/controllers’ folder.
CRUD & The 7 RESTful Actions
CRUD stands for Create, Read, Update, Delete. The 7 RESTful Actions (index, new, create, show, edit, update, destroy) of the Internet are categorized into their respective CRUD element.
There isn’t an exact order to how to use CRUD, it’s really just an acronym to remember that we need to Create things, Read things, Update things, and Destroy things. We have 7 RESTful Actions to do those things.
READ
Let’s start with R. Both the Index & Show Actions are for Read.
#INDEX
RobotsController.rb
app/views/robots/index.html.erb
Save your files! Here’s what is should look like in the browser now! (you’ve gotta type in localhost:3000/robots
to get to the Robots Index page)
#SHOW
RobotsController.rb
app/views/robots/show.html.erb
Save your files again! You should be able to click into any of the Robots and it’ll take you to each of their personal Show pages!
On the Show pages, it’ll show their Name and their favorite Slogan!
Awesome! These robots are growing on me. Let’s build a way to make more of them! 😈
CREATE
The New & Create Actions are for C in CRUD. C is for (and also named) Create.
#NEW & #CREATE
app/views/robots/new.html.erb
Save your files!
if you type and go to localhost:3000/robots/new
in your web browser, you now have a form for creating new Robots! (we’ll add a button for this later for easier access)
Now, we can create as many Robots for our Robot Army as we want! We’ll be unstoppable!
UPDATE
The Edit & Update Actions are for U in CRUD. U is for (and also named) Update.
#EDIT & #UPDATE
app/views/robots/edit.html.erb
DELETE
The Destroy Action is for D in CRUD. D is for Delete.. and to delete means we:
#DESTROY
(aka #DestroyAllHumans)
This gives us the power to destroy our Robot pals if we so choose to! I don’t know if we will, but hey, we’re the ringleader in all this so we get to decide their fate, no questions asked.
Final Touches!
In the Show page, let’s go ahead and add a“Remove Robot” button along with an Index (“All Robots”) button & an Edit (“Edit Robot”) Button:
We can also refactor (aka make the code cleaner and less messy!) the Robots Controller. We don’t like repeating ourselves, so we want “DRY” code, which stands for “Don’t Repeat Yourself” and it’s a very cool concept to start grasping now as you continue to learn how to code!
Finding the Robot ID 4 times! What?! What can definitely do better.
Let’s create a before_action
at the top of our code in the Robots Controller which will call the current_robot
method we’re creating at the bottom of the Robots Controller code (listed under private methods/actions, under our private robot_params
method).
I’ve commented out the parts where our new before_action
will takeover (therefore it’s not “active code” so it won’t be read when the code is read).
Essentially, the before_action
is what happens before the action called is actually ran (in this case, before :show, :edit, :update, or :destroy is ran, it’ll go find the robot instance we’re doing the action on at that moment).
Lastly. let’s touch up our Index page in our Views to improve the User Experience of how they go around our TaskBot Rails Application!
That’s a Wrap!
So, we now have created TaskBot: a fully functional CRUD application running on Rails!
It was definitely a quick run-through so if you’re looking for more information on a particular part, dive deeper! You can learn just about anything online or in a book (or in a coding bootcamp haha).
Either way, this was a big step.
Congratulations! The Robot Dominion thanks you for your leadership and awaits your further command (look out for Part 2!)
📝 Read this story later in Journal.
🗞 Wake up every Sunday morning to the week’s most noteworthy Tech stories, opinions, and news waiting in your inbox: Get the noteworthy newsletter >