DEV Community

Brittany
Brittany

Posted on

Day 38 - #100DaysofCode - Built my first basic rails application

Today I built a very basic rails application, I ran the following code to create my application:

rails new crud_in_rails_instruments

Then I generated my application by running:

rails g resources instrument name instrument_type rating:integer pleasant:boolean

please note that i had to change my table from type to instrument_type because type is a ruby object.

The resource generator created my model in app/models/instrument.rb:

class Instrument < ApplicationRecord
end
Enter fullscreen mode Exit fullscreen mode

It created my instrument controller in app/controllers/instruments_controller.rb

class InstrumentsController < ApplicationController
end
Enter fullscreen mode Exit fullscreen mode

In addition, it created all of the my routes in config/routes.rb

I went on to create my controller actions in app/controllers/instruments_controller.rb and my views in app/views/instruments.

Some things I learned while building this simple application is how to render a partial form in rails. I used a partial form in my edit view and new view.

First I created a partial form in app/views/instrumentstitled _form.html.erb and added the following code:

<h1>Form For</h1>
<%= form_for @instrument do |f| %>
Name: <%= f.text_field :name %>
Type: <%= f.text_field :instrument_type %>
Rating <%= f.number_field :rating %>
Pleasant? <%= f.check_box :pleasant, {:checked=>true} %>
<%= f.submit %>
<% end %>
Enter fullscreen mode Exit fullscreen mode

Then I rendered that form in my app/views/instruments/edit.html.erb and app/views/instruments/new.html.erb by adding the following code:

<%= render 'form' %>
Enter fullscreen mode Exit fullscreen mode

That simple line of code generated the form I needed on each page.

Rails makes everything easier. What would have taken me hours building in Sinatra was done a hour or two (with a few newbie hiccups)

Feel free to view my github repo containing the code. It is very simple but worth checking out :)

crud_in_rails_instruments README

This is an application with very basic CRUD functionality for created instruments.

To use

1. Forth this repo

2. Clone this repo

3. rails db:migrate

4. rails s

5. visit localhost:3000/instruments

Song of the day:

Top comments (0)