loading...

Beginners Guide to a Rails Project From Scratch

scdan0624 profile image SCDan0624 ・5 min read

Intro

Let's face it, creating a project from scratch can be a daunting task. Creating various numerous folders and files can be extremely time consuming. Luckily for us, Ruby on Rails has the ability to create the entire shell of a project from scratch in just a few lines of code. By the end of this sections you will have a complete rails project with full MVC (Model, View, Controller) abilities and full CRUD (Create,Read,Update,Delete).

Domain Model
For this project we will be working with one artist model.

Creating our project, creating the initial files and folders
The name of our project will be artist_generator. To create the project enter the following code

rails new artist_generator
Enter fullscreen mode Exit fullscreen mode

Next we will use resource to create a model, controller, migration, and route pages for our artist.

rails g resource Artist name
Enter fullscreen mode Exit fullscreen mode

You should get the following output:

      invoke  active_record
      create    db/migrate/20200302192435_create_artists.rb
      create    app/models/artist.rb
      invoke    test_unit
      create      test/models/artist_test.rb
      create      test/fixtures/artists.yml
      invoke  controller
      create    app/controllers/artists_controller.rb
      invoke    erb
      create      app/views/artists
      invoke    test_unit
      create      test/controllers/artists_controller_test.rb
      invoke    helper
      create      app/helpers/artists_helper.rb
      invoke      test_unit
      invoke    assets
      invoke      scss
      create        app/assets/stylesheets/artists.scss
      invoke  resource_route
       route    resources :artists
Enter fullscreen mode Exit fullscreen mode

Just with that one line of code we created an artist controller, artist model, empty artist view folder, and a create_artists table with a column of name.

NOTE: If you made a mistake with the naming of what you just created you can undo all of it with

rails d resource Artist name
Enter fullscreen mode Exit fullscreen mode

Now we are ready to migrate!

Migrations

code the following to migrate your table

rails db:migrate
Enter fullscreen mode Exit fullscreen mode

You should get the following schema created

ActiveRecord::Schema.define(version: 2020_03_02_211121) do

  create_table "artists", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end


Enter fullscreen mode Exit fullscreen mode

Now that our migrations are complete lets see if our server works. To get a hello/rails screen we need to have our views, controller, and routes complete. Luckily for us our rails generate code we entered earlier should have taken care of that. Lets test it out. Type the following:

rails s 
Enter fullscreen mode Exit fullscreen mode

You should see this in your command line:

=> Booting Puma
=> Rails 6.0.2.1 application starting in development 
=> Run `rails server --help` for more startup options
Puma starting in single mode...
* Version 4.3.3 (ruby 2.6.1-p33), codename: Mysterious Traveller
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://127.0.0.1:3000
* Listening on tcp://[::1]:3000
Enter fullscreen mode Exit fullscreen mode

Great lets go to http://localhost:3000/ on our web browser and you will see the following:

Rails Intro Page

Now that we know our server works lets create our index controller/views:

Creating our Index Controllers/Views

Let's start creating our artist controllers at app/controllers/artists_controller. Here we will start with a blank index method.

class ArtistsController < ApplicationController
  def index

  end

end
Enter fullscreen mode Exit fullscreen mode

Now lets go to localhost3000/artists and see our index page:

Error message

Rails is telling us we don't have a index.html.erb in the views page. So lets make one.

Go to app/views/artists and create an index.html.erb page by entering the following in the command line

touch app/views/artists/index.html.erb
Enter fullscreen mode Exit fullscreen mode

Now go back to localhost3000/artists and you will notice a blank page. This is good news! We now have a index.html.erb page we just need to fill it out with forms.

Code the following on your index.html.erb page:

<h1>Index Page</h1>
<% @artists.each do |artist| %>
    <td> Artist link:</td>
    <td><%=link_to artist.name, artist_path(artist) %></td>
<%end%>
Enter fullscreen mode Exit fullscreen mode

Let's head back to our controller page and fill out our index method.

  def index
    @artists = Artist.all
  end
Enter fullscreen mode Exit fullscreen mode

Head back to your index page and you will see the following

Index_Page

Now that we know that our index page will load we need to code a create controller and views page to allow us to create and display an artist on our index page.

Creating our Artist Create Controller/Views

#artists_controller.rb

  def new
    @artist = Artist.new
  end

  def create
    @artist = Artist.new(artist_params)

    if @artist.save
      redirect_to @artist
    else
      render :new
    end
  end

private

  def artist_params
    params.require(:artist).permit(:name)
  end
Enter fullscreen mode Exit fullscreen mode

There is a lot going on here so lets break it down.

First under the private section we added a method for artist params. By adding it under private it provides an interface for protecting attributes from end-user assignment.

Next we created an create method that if the artists is successfully created and saved it will redirect you to the artist show page (which we will create later). If it is not saved it will render the new page again.

Next lets create our new.html.erb page.

First create the view page:

touch app/views/new.html.erb
Enter fullscreen mode Exit fullscreen mode

Next code the following on the page:

<h1>Create an Artist</h1>

<%= form_for @artist  do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <br />

  <%= f.submit %>
<% end %>

Enter fullscreen mode Exit fullscreen mode

This will show the following on localhost3000/artists/new:

Create page

Next lets code our show controllers/views

Creating Artist Show Controller/Views

Lets start by creating a show method:

  def show
    @artist = Artist.find(params[:id])
  end
Enter fullscreen mode Exit fullscreen mode

Next lets fill out the show.html.erb page

touch app/views/artists/show.html.erb
Enter fullscreen mode Exit fullscreen mode
#show.html.erb

<h1>Show Page</h1>

<h1><%= @artist.name %></h1>

<%= link_to 'Home', artists_path%>

Enter fullscreen mode Exit fullscreen mode

Now once you create an artist it will take you to the show page of that artist. If you click on the home button on the show page it will take you back to the index page.

Creating Edit/Update

Lets head back to our controller and create an edit and update method

#app/controllers/artists_controller.rb
  def edit
    @artist = Artist.find(params[:id])
  end

  def update
    @artist = Artist.find(params[:id])

    @artist.update(artist_params)

    if @artist.save
      redirect_to @artist
    else
      render :edit
    end
  end

Enter fullscreen mode Exit fullscreen mode

The edit method just requires us to find the current artists we are trying to edit. The update method we first find the artist and if the artist is found we update and redirect to the show page. Otherwise we render the edit page again (which we will make next)

Now that we have our controller completed we will create our edit.html page which is where we will edit and update our artist.

touch app/views/artist/edit.html.erb
Enter fullscreen mode Exit fullscreen mode
#app/views/artist/edit.html.erb

<h1>Editing <%= @artist.name %></h1>

<%= form_for @artist  do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <br />

  <%= f.submit %>
<% end %>

Enter fullscreen mode Exit fullscreen mode

Now if we change the name of our artist it will save the change and send us back to the show page.

But what if we want to go to the edit page from the show page? One line of code will fix that.

<h1>Show Page</h1>

<h1><%= @artist.name %></h1>

<%= link_to 'Home', artists_path%>
#new code
<%= link_to 'Edit', edit_artist_path(@artist)%>
Enter fullscreen mode Exit fullscreen mode

Now we can create, edit, and update our artist. The last thing we need to do is be able to delete an artist.

Deleting an Artist
First add the following code to the bottom of your show page. This will add a delete button.

<%= button_to "Delete", artist_path(@artist), method: :delete %>
Enter fullscreen mode Exit fullscreen mode

Now we just need to make our destroy controller. Lets create a destroy method and add it to our artist controller:

  def destroy
    @artist = Artist.find(params[:id])
    @artist.destroy
    flash[:notice] = "Artist has been deleted."
    redirect_to artists_path
  end

Enter fullscreen mode Exit fullscreen mode

The following method will find then destroy the current artist. It will then alert the user that the artist has been deleted.

You've done it, you have created a full CRUD app from scratch using Rails

Alt Text

Discussion

pic
Editor guide