Ruby on Rails – create new from web

When you create an @variable as opposed to a variable, the @ tells that it is an instance variable.

By opening config > routes.rb, we can use the code resources :articles to give a lot of different paths to articles (index, create, new, edit, show, update, and destroy).

A nice thing about Ruby on Rails is the program kind of tells you what to work on next.  We want to do a new article, so if I type in my browser: 0.0.0.0:3000/articles/new, it will tell me why it can’t do that (no route).  So go to route.rb and give it the resources to do it.  Reload the page and see that it says uninitialized ArticleController.  Guess where we go next?  Yup.  App > Controllers > new file > “articles_controller.rb”.  The code is as follows:
class ArticlesController < ApplicationController
  def new
  end
end
Save it and reload 0.0.0.0:3000/articles/new.  Now it is missing the template (view).  Go to views and create a new folder called articles.  Inside that folder create a file called new.html.erb.  Put a <h1> at the top telling what the page will do: “Create a new article”.  Reload the site and see if you can see the <h1>.  And we can!  Perfect.  Now we need to create a form to put on that page so the user can create a new article.  RailsGuides has a great site talking about all the parts of forms that rails provides but for now we’re just going to do some basic things.

So on the new.html.erb file, type:
<h1>Create a new article</h1>
<%= form_for @article do |f| %>
<% end %>
When you save and run this, you’ll see an error.  It says the first argument can’t be empty (because we haven’t made @article yet).  So we need to go to articles_controller.rb and create it.  So now it should have:
class ArticlesController < ApplicationController
  def new
    @article = Article.new
  end
end
Since we got all of that working, we can now build the form on new.html.erb.
<h1>Create a new article</h1>
<%= form_for @article do |f| %>
  <p>
    <%= f.label :title %><br/>
    <%= f.text_field :title %>
  </p>
  <p>
    <%= f.label :description %>
    <%= f.text_area :description %>
  </p>
  <p>
    <%= f.submit %>
  </p>
<% end %>
Everything works, but when you try to click “Create Article” it won’t work.  The error says “action create couldn’t be found in ArticlesController”.  So we need to define create in ArticlesController.  That is done by typing:
class ArticlesController < ApplicationController
  def new
  end
  def create
    #this will show you what is happening, but just comment it out
    #render plain: params[:article].inspect
    @article = Article.new(article_params)
    if @article.save
      flash[:notice] = "Article successfully created
      redirect_to articles_path(@article)
    else
      render 'new'
    end
  end
     
  private
    def article_params
      params:require(:article).permit(:title, :description)
    end
end

The next thing we need to do is figure out how to deal with flash[:notice].  Views > layouts > application.html.erb is a wrapper for all the pages, so we’ll see this html code on all pages.  This would be a good place to put our notice messages.  So in the body of that page (right above <%= yield %>, put:
<% flash.each do |name, msg| %>
  <ul>
    <li><%= msg %></li>
  </ul>
<% end %>

This all looks good but we don’t have a way of displaying the errors or the validations that occur when you click “Create Article”.  We can fix that by entering some code on the new.html.erb page.  Right below h1, put:
<% if @article.errors.any? %>
<h2>The following errors prevented the article from getting created:</h2>
  <ul>
    <% @article.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
    <% end %>
  </ul>
<% end %>

Now when I try to create an article with no title, I do get which errors are occurring so that I know why I can’t make an article.  But when I put in a correct title and description, I get a message “The action ‘show’ could not be found in ArticlesController.”  So I need to define show in ArticlesController found in app > controllers > articles_controller.rb.  It doesn’t seem to matter where I place the define, but I’m going to put it right below create.
def show
  @article = Article.find(params[:id])
end
You now have the action, but are still missing the template.  So go create that under app > view > articles > create a new file called show.html.erb.  On that file, we need to type the code to place the info on that page:
<h1>Showing selected articles</h1>
<p>
  Title: <%= @article.title %>
</p>
<p>
  Description: <%= @article.description %>
</p>

That should be it!  We can now create articles by going to 0.0.0.0:3000/articles/new.  Make sure to commit and push to git and we are done for now.  Next entry will be about editing entries.  

Read More

Ruby on Rails – edit/delete entries & validations

This entire section and the previous article has been working with the backend of my app.  Eventually I will be able to do all of these things from the browser, but for now I need to understand how this works from the backend.

In order to edit an entry in a database, you first need to grab it.  You can grab it by assigning it to a variablearticle = Article.find(2), where 2 is the article’s ID.  Then all you have to do is typearticle.title = "This is the new title of the 2nd article", then type: article.save to save the change.  If you want to see that change, typeArticle.all.  If you want to delete an entry, grab the article just like we did before, and then type: article.destroy to delete it.

The way our app is currently set up, people can enter blank entries to clog up the app.  We don’t want that so we need to set validations at the model layer to maintain data integrity.  We want to make sure that all entries have a title and a description.  The validation needs to be added to app > models > article.rb.  The code should be: 
class Article < ApplicationRecord
  validates :title, presence: true
end
What this does is makes sure that the title of an entry has a value.  If it doesn’t, then it won’t be allowed to be submitted to the database.  In order for this to work, you do have to restart the rails console so make sure to exit it and restart it before you try.  You can also type reload! to restart the console.  One more constraint we want to add on is to make sure it has a minimum of 3 characters and a maximum of 50 (we don’t want a letter or an entire paragraph as a title…) So the additional code is:
class Article < ApplicationRecord
  validates :title, presence: true, length: { minimum: 3, maximum: 50 }
end

Now if you try to create an article without a title or the title is too short or long, there will be an error when you try to save it using article.save.  If you are curious of what the error is (it doesn’t tell you right off) then you have to type: article.errors.full_messages and it will tell you what went wrong.

And don’t forget to push changes to git.  Use git status to see what files have changed without having been committed. git add -A will add those files to a commit.  Then use git commit -m "your message" to actually add the changes to the commit and then use git push to push the changes.

Read More

Ruby on Rails – tables/databases

If you have a table that will be holding a bunch of articles for a blog, the title of that table is articles.  The model name will be the singular, so Article (and it should be capitalized).

Table = plural, lowercase of the model name => articles
Model = singular, first letter capitalized of the table name => Article
Model file name = should be lowercase, singular with .rb at the end => article.rb
Controller name = plural of model file name => articles_controller.rb
Filename should always be snake_case.
Model & class names should be CamelCase.

To generate a table:
rails generate migration create_articles

This creates a table in your alpha-blog > db > migrate folder called (a bunch of numbers)_create_articles.rb.  When you open this up you’ll see a table, but you need columns.  It has the code:
create_table :articles do |t|
To add a column and put the header of “title” on it, we need to add this code:
create_table :articles do |t|
  t.string :title

You could also have added a column to hold the article’s text (or description) by doing this code:
create_table :articles do |t|
  t.string :title
  t.text :description

but we’ll leave it out and add it later to show what to do in case you need to add a column once a table has been created.

We then need to run rails db:migrate to actually create the table.  Once that is done you’ll see code in db > migrate > schema.rb that shows the “articles” table. But we forgot to add the description column, so we have a few options of how to fix that.  I can run rails db:rollback which essentially is like command-z.  I can then add the description and run rails db:migrate again.  Even though this works, it isn’t the best way to deal with a mistake.  Instead, you should create a new migration file. To do this, enter rails generate migration add_description_to_articles.  Once this new migration is created, you need to open it: db > migrate > (bunch of numbers)_add_description_to_articles.rb and add some code to create columns.
def change
  add_column :articles, :description, :text
  add_column :articles, :created_at, :datetime
  add_column :articles, :updated_at, :datetime

What this just did was added 3 columns to our table titled “Description”, “Created At”, and “Updated At”.
Once this is done, you need to migrate the db again. rails db:migrate.

Once that is finished, you can go back to schema.rb and see the changes that occured.  We’ve created the database, but we need a model to be able to communicate with the database.  This is the image used in the course to help understand the relationships between all the pieces.

image from the Complete Ruby on Rails Developer Course – Mashrur Hossain

So we need to create a model to communicate with the database.  That is done under app > models > create new file called article.rb.  In that new file, you’ll need to put the code:
class Article < ApplicationRecord
end

Rails magically creates getters and setters for each of the columns we made earlier in the table once we make this model.

You can check to make sure this worked from rails console. This gives you direct access to your database. You can use it as a playground to test things out. If you type in Article.all it will show you if there is a connection. You can then type Article to see all the attributes. There are a lot of things you can do from here, but they are referenced in the video of section 4, lecture 46 at around 15:30.  But a few of the commands are:
article = Article.new
article.title = "This is my first article"
article.description = "This is the description
article.save
Another way to do this more succinctly is:
article = Article.new(title: "This is my 2nd article.", description: "This is the 2nd description." and then save.
Article.create(title: "This is my 3rd article.", description: "My 3rd description.") – this one you don’t have to save as the create method automatically saves it. This is probably the most effective method.
To get out of the rails console, just type exit.

Read More

Ruby on Rails – deploying to Heroku

To deploy to Heroku, follow these steps:

  1. Open the Gemfile in your app.  Heroku doesn’t support sqlite3 (they support postgresql) so we have to change that.  Remove gem 'sqlite3' and put it near the bottom under group :development do
  2. At the very bottom of Gemfile, type
    group :production do
    gem 'pg'
    end
This lets us use postgresql while developing but sqlite3 when we actually produce.

To get this to actually take effect, we need to commit to our repository.  We do this by typing this in shell: bundle install --without production.  Then log in to heroku.com and find instructions for installing heroku toolbelt on local machine.  The course wasn’t clear about how to install locally, but I think this code should do it. curl https://cli-assets.heroku.com/install.sh | sh. I think the piece we are trying to install is called CLI (used to be called Toolbelt?). Type heroku -v to make sure heroku was installed correctly.

Now log in to heroku using heroku login. You’ll be redirected to a browser to login. We need to create an application in heroku for our application. To do that, use heroku create. If you then use git status you’ll see what hasn’t been committed and what has. Remember to use git add -a and git commit -m "whatever you want the message to be" to add the changed files to your commit.

Lastly, we need to add our ssh key to heroku.  If I don’t, it will continually ask me for my username and password.  Just use the codeheroku keys:add.   Once this is done, you should be able to push your application to heroku. When I tried to push the application to heroku, I ran into an issue because bundler had been upgraded to bundler 2.  I first had to run this command:  heroku buildpacks:set https://github.com/bundler/heroku-buildpack-bundler2 but then after that, I was able to git push heroku master to send the app to heroku.

That is completed and here is the site. To rename the site, use the code: heroku rename new-name-of-site (whatever you want it to be).

Read More

Ruby on Rails – Git & Github

I’m just using this to document what I’m doing to help solidify the work in my head. I’m also likely to come back here to reference different steps…

To be able to back up and save your program, I’m going to use github.com. The first thing you have to do is set up your ssh (which stands for secure shell). You can use the command cat ~/.ssh/id_rsa.pub in the terminal. You then have to copy the code that is printed. Got to github, click to add a new SSH, and paste the code into the field. Once that is done, you should make a repository for each of the programs you will work on.

To create a new repository, you need to click on the “+” sign in the top right corner of github.com and choose “New repository”.  Name the repository something that makes sense (probably the name of your program).  You’ll then want to follow the instructions to “push an existing repository from the command line”.

Before you can actually “push” your changes to a repository with git, you have to “commit” the changes. git status can always show you what files have been modified. Use git add -A to add a file to your local repository (local repo). Then use git commit -m "note to remind you what this is for" to commit that local repo. This just “saves” your changes, but it hasn’t uploaded it to github. To “upload” it to github, use git push to push the files to github.

Right now, I’m able to fire up a rails server and see what I’ve created in my own browser, but that is all local, nothing to show others or see online.  If I want to be able to show it to others, I need to deploy to production.  I’ll be using Heroku (which is a very common site to use) for this.

Read More

Notes for Rails – creating a new page

Just for those following along, I’m learning how to create a new app: How to create a new Rails application: rails new test_app (where “test_app” is the name of the program) and add an html to that page.

I first have to make a new route in the config folder in my new app.  I do that by loading my app in Atom (or a similar editor) and drilling down in the file tree to the config folder.  Open routes.rb and create a new path by typing get 'pages/home', to: 'pages#home'. This creates the route, but now I’ll need a controller and a view. To create a controller, find the controllers folder which is nested inside the app folder. Inside that folder, I’ll need to make a new file called pages_controller.rb. Once that file is created, I’ll need to put the following code in to inherit the stuff from the ApplicationController:
class PagesController < ApplicationController
end

Then inside the pages_controller.rb file and inside the class PagesController, I’ll need to define the action(method): home.
class PagesController < ApplicationController
  def home
  end
end

The last thing I need to create is the template for the page. Navigate to the views folder and create a new folder titled pages. Inside that folder create a new file titled home.html.erb. That page is the actual webpage, so put “This is the home page”(or whatever you want).

One additional note: to add a ruby code to a .erb file, you have to put the code between <% and %> brackets.  If you want the code to actually show something on the screen of a web browser, the open bracket should be <%= and closing should be %>.  A link would be: <%= link_to 'Home Page', pages_home_path %> where 'Home Page' (is the text that will be the link) and pages_home_path is the path to the controller (pages) and the action or method (home) - which will get you to the actual Home Page.  Don't forget the comma between the two (I wasted 15 minutes forgetting that earlier)...

Also... instead of having to type 0.0.0.0:3000 to see the rails server, and then having to type 0.0.0.0:3000/pages/home to get to the home page, you can make 0.0.0.0:3000 be the home page.  You just have to go to the routes.rb (in the config folder and change the code from this:
get 'pages/home', to: 'pages#home' 
to this:
root 'pages#home'.
Once that is changed, make sure to update the path to <%= link_to 'Home Page', root_path %>

Read More

Ruby on Rails – progress #1

Image result for ruby on rails image

I’ve been enjoying the Udemy course so far, learning about methods, arrays, branching, iterators, and hashes.  So far things have made sense, and there have been a few small projects to work through that have made sense.  My brother gave me another suggestion today for another course.  This one is from FlatIron School and is called Coding Bootcamp Prep.  There also looks to be an Intro to Ruby but I’m guessing that what I’m learning with the Udemy course would cover all the basics.  I’m looking forward to having enough knowledge under my belt to start making my own program.  The course also gave another recommendation of a site to hone your basic skills: GitHub TryRuby.  Seems pretty doable.

Read More

Ruby on Rails – installation

I decided to take the plunge and shell out the $10 for a $200 Udemy class.  It has a lot of good ratings and I think it will be a good way to get to learn more about Ruby on Rails.  There are over 40 hours of video instructions and I’ve been able to follow along quite easily with them so far.  I’ve found that I’ve been watching a lot of TV recently and decided that I should probably cut back a bit or at least multitask and learn something with the extra time.  So Rails it is.  

My main goal is write a web app that will allow me to keep track of my Singles Tennis Ladder in a cleaner nicer way.  I think that should be pretty doable.  Another project I could work on is an attendance program for school (which we surprisingly don’t currently have).

The first thing I had to do was update my version of Ruby and Rails (and Homebrew) but after some googling, I was able to do it pretty easily.  I did have a slight hiccup with Homebrew. I kept getting an error that I didn’t have permission to write to /usr/local/, but after uninstalling and reinstalling, that took care of the issue.  I finally got it installed on my local machine and I’m ready to start learning some Rails!

Read More

Ruby on Rails

I’ve always been interested in coding and try to teach myself different languages at different times.  I’ve dabbled in Ruby a while ago, but don’t remember a ton.  But I want to get better and would like to write a web app for our Tennis Singles Ladder (which is currently running using a Google Sheet).  It works for what we need it for, but I thought it would be nice to convert it to something a little bit shinier (and a project for me to build while learning a language).  But to start, I need a short refresher course.  So I googled the best ways to learn Ruby.  I’m going to keep some sites referenced here but also will try to write down some of what I’m learning.

Ruby Warrior is a cool little game that has increasingly difficult levels that require you to write code to have your knight work his way through a dungeon.  If you’ve never learned any coding or Ruby, this probably isn’t the place to start as there really isn’t any teaching.  I’ve been able to fumble my way through the first six levels so far with just a bit of youtube help.  If anything it is learning through watching other people succeed and copying what they are doing.  Not sure if it will be super helpful with my end goal, but it is a fun way to remember certain aspects of Ruby.

Other sites to eventually check out:
Udemy – offering $200 courses for $10 this week
The Odin Project
Thoughtbot – Upcase – recommended by my brother

Read More