From Form to Database

Most websites will have forms on them. From asking a user to login to having a user sign up for a mass email. How does the information a user enter on your website get stored so you can access the user’s information later?

First we need to build a form for the user to input their information.

   
<form method="post" action="email.php">
     <div class="formRow">
          <label for="first_name">First Name:</label>
          <input type="text" name="first_name">
     </div>

     <div class="formRow"> 
          <label for="last_name">Last Name:</label>
          <input type="text" name="last_name">
     </div>

     <div class="formRow"> 
          <label for="email">Email Address:</label>
          <input type="email" name="email">
     </div>

     <div class="formRow"> 
          <input class="btn btn-primary" type="submit" value="Submit">
     </div>
</form>

Above we are using the HTML <form></form> element. This element has two attributes, the “method” and “action” attributes. The “method” attribute here is set to “post” which means that we want to send the data we receive from the user through an HTTP request to our database. The next attribute on this form is the “action” attribute. The “action” attribute specifies where the data should be sent when the user hits submit. Here we want the data from the form to be sent to a php file called “email.php”. The “email.php” file will have all the code we need to connect to our database and process the form data.

Inside our we have two more HTML form elements. The first element is the <label></label> element. This is used as a label for out next element, the <input> element. The way that the <label></label> element knows which <input> it is associated with is by the “for” attribute. Now when we look at our <input> element we notice that there is an attribute called “name” which is set to the same value as the “for” attribute in the <label></label> element. The element also has a “type” attribute. This attribute is going to specify what kind of input the user is allowed to put into the input field.

<label for="first_name">First Name:</label>
<input type="text" name="first_name">

In our HTML form example for “first_name” we set “type” to equal “text”. This means that the user must enter text into this input field. The other input values for “type” are: button, checkbox, color, date, datetime-local, email, file, hidden, image, month, number, password, radio, range, reset, search, submit, tel, text, time, url and week.

There are two more input fields in our form that accept user data, the “last_name” and “email” input fields. Those are just about the same as the “first_name” field so lets skip down to the bottom of our form and look at the “submit” input. Notice that this input does not have a label. This doesn’t need a label, because the “value” attribute on this input field will be printed to the screen. For example here the user will see the text “Submit”. When the user hits the “submit” input field this will send the user to the “email.php” file which we specified up at the top of form as our action.

<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "useremails"; $first_name = $_POST['first_name']; $last_name = $_POST['last_name']; $email = $_POST['email']; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) {
	    die("Connection failed: " . $conn->connect_error);
	} 

	$sql = "INSERT INTO orders (first_name, last_name, email)
	VALUES ('$first_name', '$last_name', '$shipping_address', '$email')";

	if ($conn->query($sql) === TRUE) {
	    echo "New record created successfully";
	} else {
	    echo "Error: " . $sql . "
" . $conn->error;
	}

	$conn->close();
?>

In the code above we are now processing the data that the user has submitted and placing that data into our database.

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "useremails";

These four php variables are set to equal all the information we need to access our database. We define our server’s name as “localhost”, our user name to “root”, our password as an empty string, and lastly we define our database name to “useremails”.
* Note: You will have to change these variables to your own credentials for your database.

$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];

Now we take the input that the user entered into the form and save those inputs as php variables. We set our form method to “post” which sent the data and now in php we are able to access that data through php’s predefined variable “$_POST”. “$_POST” saves the user’s data into an object. We can access the values that the users have entered by using our input field’s “name” value as the keys ($_POST[‘first_name’]).

$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
} 

The next block of code is how we connect to our database. “new mysqli()” is how we open a new connection and the four arguments that it takes is our information for our database. Then we check to see if there was an error connecting to the database and if there was we want the process of trying to connect to end.

$sql = "INSERT INTO emails (first_name, last_name, email)
VALUES ('$first_name', '$last_name', '$email')";

Once our connection to our database is established we are able to add the user data into our database. This is done by writing an SQL query to the data. Above we are saying that we want to “INSERT INTO” our “emails” table the three values “$first_name”, “$last_name” and “$email” into our table with the column names of “first_name”, “last_name” and “email”.

if ($conn->query($sql) === TRUE) {
     echo "New record created successfully";
} else {
     echo "Error: " . $sql . " " . $conn->error;
}

$conn->close();

Our last step is to see if our data was successfully submitted to the database. If “$conn->query($sql) === TRUE” evaluates to true then we print “New record created successfully” to the screen and if not then we will print an error to the screen. After we see if our data was saved correctly or not the connection to the database is closed.

Working with Qunit

mic

Have you ever been working on a site and think everything is going great until you view your site locally? Maybe you find your images are no longer showing up or an element isn’t floating the way you thought it would. You can see on the browser what the problem is, but maybe it takes you a lot longer to find what the cause of the problem is when you look at your code. There have been times when a simple misplaced semicolon has caused hours of pain. This is why unit testing is so important. You can create tests for your code and if something breaks while you are developing your site the test will alert you that something has broken. This makes it a lot easier to go back to your code and fix the problem. There are many ways to write tests for your code depending on what language you are working with. I want to focus on JavaScript in this blog post so we are going to look at QUnit for creating tests.

A good place to start is to look at the documentation for QUnit. Here you will be able to find examples as well as download the documents you need to create your own test. You will have to download the first two files and place them into your sites directory.

Screen Shot 2014-11-30 at 6.33.36 PM

We are also going to be referring back to the API documentation a lot, because it contains a full list of all the assertions we can use to create tests. What if you wanted to make sure that two objects were equal? You could use the “propEqual” assertion. Below is an example of using “propEqual”.

First we need to set up our html file.

<!DOCTYPE html>
<html>
<head>
     <meta charset="utf-8">
     <title>propEqual Example</title>
     <link rel="stylesheet" href="qunit-1.15.0.css">
</head>
     <body>

          <div id="qunit"></div>
          <div id="qunit-fixture"></div>

          <script src="qunit-1.15.0.js"></script>
          <script src="propEqualTest.js"></script>
     </body>
</html>

Above in the <head> tag of the document we have a link to the css file that we downloaded from the QUnit site. At the bottom of the <body> tag we are linking to two JavaScript files. The first file is also downloaded from the QUnit site and the second file is one that we are going to create all of our tests in. Lets add some tests in the “propEqualTest.js” file.

test('testing propEqual', function() {
 propEqual( {animal: 'tiger'}, {animal: 'tiger'}, 'same objects, test passes');
 propEqual( {fish: 'goldfish'}, {fish: 'dog'}, 'not the same, test fails');
})

Above we have a function called “test” which gets called from the “qunit-1.15.0.js” file. This function has two arguments. The first argument is a string which is just labeling the test we are creating. The second argument is a callback function which is where we are using “propEqual” to create the test. The “propEqual” assertion is defined in the API documentation. What we are doing above is comparing the first two arguments of the “propEqual” assertion with each other. If the objects are the same the test will pass, because it evaluates to true and if they don’t match they will evaluate to false. Now lets look at how the html document looks when we open it in a browser.

Screen Shot 2014-11-30 at 7.07.00 PM

The first test passed and we see that our message “same objects, test passes” in green. The second test failed so we see our message “not the same, test fails” appear in red. We also see what the differences were between the two objects which caused our test to fail. You can see how helpful writing tests becomes when working on developing a site.

Below is a list of resources for QUnit:

Make a carousel using Javascript

horse

There are many ways to create slideshows for your website. You could use the carousel that Bootstrap has in their JavaScript section. The JavaScript library jQuery is also another great way to create a carousel. In this post though we are going to use JavaScript for the functionality of our carousel.

First we are going to create an html document to give our carousel a home.


<!DOCTYPE html>
<html>
     <head>
          <title>Slideshow</title>
          <link rel="stylesheet" type="text/css" href="css/styles_slideshow.css">
     </head>
     <body onload='runSlideshow()'>

          <header>
               <h1>JavaScript Slideshow<h1>
          </header>

          <div id="viewer">
               <div>
                    <img id="arrow_left" src="img/left_arrow.png" alt="left arrow">
               </div>
               <div>
                    <img id="arrow_right" src="img/right_arrow.png" alt="right arrow">
               </div>
               <div class="image">
                    <img id="image_1" src="img/image_1.JPG" alt="beach with hills in the background"/>
               </div>
          </div>

          <footer>
               <p>Christina Cannito - JavaScript Slideshow - 2014</p>
          </footer>
     <script type="text/javascript" src="js/slideshow.js"></script>
     </body>
</html>

Above we have a simple html page to get us started on our carousel. Inside the <head> tag we have the <title> of the html page and a link to a CSS style sheet. After the head we go to the <body> tag where there is “onload=’runSlideshow()'”. What this means is that as soon as the body loads the “runSlideshow” function is going to be called. That function is defined in our JavaScript file, which we will be looking at shortly. Inside the body we have a <header> tag,  a div with an id of “viewer” which has several divs inside of it, a <footer> tag and lastly a link to our JavaScript file.

The div with the id of “viewer” is going to be where all the images for our carousel will be displayed. The next two divs inside “viewer” hold our left and right arrows. Lastly there is a div which holds a placeholder image with the class of “image”. Now lets see how JavaScript works with this page to set the carousel in motion.


"use strict";

var index_num = 0;
var image_array = ["image_1", "image_2", "image_3", "image_4", "image_5"];
var leftClick = document.getElementById('arrow_left');
var rightClick = document.getElementById('arrow_right');
var imageViewer = document.getElementById('image_1');

function createLinkedImage(domContainer, imgArray, index){
     domContainer.src = './img/' + imgArray[index] + '.JPG';
}

function runSlideshow() {
     leftClick.addEventListener('click', function(){
          if (index_num === 0) {
               index_num = image_array.length - 1;
               createLinkedImage(imageViewer, image_array, index_num);
          } else {
               index_num = index_num - 1;
               createLinkedImage(imageViewer, image_array, index_num);
          }
     }, true)

     rightClick.addEventListener('click', function(){
          if (index_num === image_array.length) {
               index_num = index_num - 1;
               createLinkedImage(imageViewer, image_array, index_num);
               index_num = 0;
          } else {
               createLinkedImage(imageViewer, image_array, index_num);
               index_num = index_num + 1;
          }
     }, true)

     setInterval(function(){
          if (index_num > image_array.length - 1) {
             index_num = 0;
             createLinkedImage(imageViewer, image_array, index_num);
          }
          createLinkedImage(imageViewer, image_array, index_num);
          index_num = index_num + 1;
     }, 3000);
}

Lets start by looking at the variables that are defined at the top of the document.

  • var index = 0; This is how we are going to keep track of the index number as we iterate over the array of images that we want to display.
  • var image_array = [“image_1”, “image_2”, “image_3”, “image_4”, “image_5”]; An array of all the images that we are going to display.
  • var leftClick = document.getElementById(‘arrow_left’); We are targeting the the element in the html document with the id of “arrow_left”.
  • var rightClick = document.getElementById(‘arrow_right’); Here we are doing the same thing as “leftClick”, but we are targeting the element with the id of “arrow_right”.
  • var imageViewer = document.getElementById(‘image_1’); Targeting the element with the id of “image_1” which is going to display our images.

We are going to use these variables throughout our JavaScript document. This is going to save us a lot of writing, because we can simple plug in these variables where we need them. Next we see a function called “createLinkedImage”. As we iterate through the array we are going to create new links to those images. The way the links are generated is by what we are passing into this function. This function takes in “domContainer” which is where we want the images to be displayed and we saved that information to the variable “imageViewer”. Also we have to pass in where we get the image information, which is inside our “imageArray”. The last argument we pass into this function is the “index”, which is going to be the index number. The index number is going to determine what image in the array will appear. This function gets called inside the “runSlideshow” function.

The “runSlideshow” function is going to get called as soon as the body of our html page is loaded. If a person does not click on either the left or right arrows our “setInterval” function is going to run. Inside this function we have a conditional statement. That statement says if the index number is greater than the amount of elements in the array we are going to reset the index back to zero. If the index number is less than the amount of elements in the array we will show that image and add one to the index number.

There are two click events that will handle if a person clicks on the left or right arrows. We are always updating the index_num variable in the “setInterval” function and we use that same variable in our two click events. If a person clicks on the right arrow while on the first object in the array we will show that image by calling the “createLinkedImage” function then add one to the index_num variable. If a person clicks left we will subtract one.

Asset Pipeline

assets_pipeline

Rails allows you to manage your CSS, JavaScript and images through the assets pipeline. Why would you want to manage your files this way? The assets pipeline lets you organize your CSS and JavaScript files with a file called the “manifest” file. For CSS the file is called, “application.css” and for JavaScript it is called, “application.js”. These two files are where you would link all of your CSS and JS files for your entire application. For example instead of linking your CSS in the head of your HTML document you can put all your CSS in the “application.css” file and those files will linked to your HTML documents. If you had many HMTL documents that required the same CSS file you would only have to write it once in the “application.css” file. If you require all of your CSS and JavaScript files through the manifest file they will compressed into one file. (The CSS will be compressed into one file and the same would go for your JavaScript.) This is great, because if you are only rendering one CSS file and one JavaScript file when your application gets loaded in the browser your application is going to load much faster. Basically one large CSS file and JavaScript file is better than ten small files.

Here are some basics about the “application.css” file: Screen Shot 2014-08-03 at 2.32.22 PM

  • When you first create your Rails application your “application.css” file is already in your app! It can be found in the app/assets/stylesheets directory.
  • When you open up this file you should see the following: Screen Shot 2014-08-03 at 2.35.01 PM
  • Most of what is here are comments about the file and can be delete. (All the comments are from line 2 – line 11).
  • Line 13 has: “*= require_tree .” This means require all CSS files that are in this directory.
    • When you use “*= require_tree .” your CSS files are going to be loaded in the order that they are currently in. This means that if your CSS files are being listed alphabetically that they will be required in that same order. If you want your CSS files loaded in a certain order then you would have to list them here manually.
    • To list your CSS files manually you would have to write them the following way. Screen Shot 2014-08-03 at 2.51.38 PM
    • Above I took out “require_tree .” and instead wrote out the names of my CSS files in the order that I would like them to be loaded in. If I didn’t do this and kept “require_tree .” then the file would have been loaded as “example_1” then “example_2”.
    • Note: you do not need to include the file extensions when you require your files in the manifest file.
  • Line 14 has: “*= require_self” This means that the file is going to require itself!

Here the “application.js” file: Screen Shot 2014-08-03 at 2.56.08 PM

  • The “application.js” file can be found in the app/assets/javascripts directory.
  • Here is how the “application.js” file will look when you first open it: Screen Shot 2014-08-03 at 2.57.43 PM
  • It is pretty similar to our “application.css” file. This file also contains a “require_tree .” which will do the same thing as in our “application.css” file.
  • This file also has comments which you can remove if you would like. (Comments are from line 1 – line 11)
  • Inside your “application.js” file there are some default JavaScript files that are going to be loaded into your application.
  • What if you wanted to load your JavaScript files in a specific order? You can require them individually and remover the “require_tree .”.Screen Shot 2014-08-03 at 3.02.58 PM

How do we tell if our files are being required?

  • Make sure that you have your Rails server running. Type in “rails s” in the root directory of your application in your terminal.
  • Go to view your application in the browser. Usually the default port number is “3000”, but you can always double check what port you are on by looking at your terminal when you run the rails server. Screen Shot 2014-08-03 at 3.14.40 PM
  • Above I typed in “localhost:3000” which is where my application is running on my local server. Then I typed in “/?debug_assets=1”
  • After you type that in and press enter you will want to view the source code for your application.
  • To view the source code you go to the menu bar for your browser, go to “view”, then “developer” and click “view source”. (This is for Chrome)
  • After you click “view source” a new window should appear with all the source code for the page you are viewing. Here is my source code: Screen Shot 2014-08-03 at 3.18.26 PM
  • Notice that all my CSS and JavaScript are included in the “head” section of my html.erb file. The only place that I had these files listed in my application was in my manifest files.
  • Also notice that all the files are listed in the order that I have specified them in. “example_2.css” being listed before “example_1.css” and the same is happening for my JavaScript files.

Image if I had a ton of CSS and JavaScript files that I wanted to include on multiple pages and wanted them in a certain order when they were loaded. By using the asset pipeline it is very easy to make sure all my files are included and in the correct order.

Creating user log in

login

In this blog post we are going to create a way for users to log into an app from scratch.

As all apps begin in the terminal. Type into the terminal: rails new login_appScreen Shot 2014-07-28 at 11.16.39 AM

You will see once you type that in and press “enter” that a lot of files were created

Then in your terminal you will want to go into this new folder that you created. Type in your terminal: “cd login_app”

Then if you type “ls” you will see all the new files and folders that were created. Screen Shot 2014-07-28 at 11.20.44 AM

Then if you type in”rails s”, which is short for “rails server” you will see the following:  Screen Shot 2014-07-28 at 11.22.28 AM

See where it says “Rails 4.1.4 application starting in development” this means that your app is now running on you local server and if you type in “localhost:3000” into your browser you will see your app! Screen Shot 2014-07-28 at 11.25.14 AM

Here is our app! Right now it doesn’t look like much, because we have applied any views or code in general, so lets fix that!

If you had started your server and want to stop it. To stop the server press “control + c” (this is for Mac users)

Then if you are using “Sublime Text” as your text editor in the terminal there is a nice shortcut to open up the application in the text editor. Type: subl .Screen Shot 2014-07-28 at 11.29.20 AM

Then in “Sublime” you should see the following: Screen Shot 2014-07-28 at 11.30.38 AM

These are all the files and folders that we received when we typed “rails new login_app”

The first file I want to look at is the “Gemfile” where all the gems are that are going to be used for this app. You can find this in the main directory of your app. Screen Shot 2014-07-28 at 11.34.00 AM

Notice towards the bottom of the document there is a commented out gem called “bcrypt”. This is an extremely important gem! You never want to store passwords in plain text in your database! The reason you never want to is because incase someone breaks into your database all the usernames and passwords can be taken. If people use the same username and password for multiple accounts then you have also compromised there information on those other sites. What “bcrypt” does is encrypt the users passwords so that what gets stored in the database will not look like what the user has entered. This is a very popular gem to use for passwords, incase you want to learn more about this gem here is a nice resource: codahale/bcrypt-ruby

To uncomment out something in Ruby just remove the “#” sign. After you do that then you should see the text in color! Screen Shot 2014-07-28 at 11.43.19 AM

Whenever you add or adjust a gem in your gem file you have to go back to the terminal to the root of your application and type in: “bundle install”

After you run bundle install your should see:Screen Shot 2014-07-28 at 11.45.45 AM

You will know if the bundle was successful if you see this at the bottom: Screen Shot 2014-07-28 at 11.47.19 AM

Now that we are set up with the “bcrypt” gem which will store passwords in our database safely, lets set up our database!

In the terminal type in: “rails g migration Users”

The “g” is short for generate

Lets go back to Sublime and see what this created! Screen Shot 2014-07-28 at 11.59.20 AM

  • In “db”, then in the folder “migrate” you will see there is a new file there with the file name “20140728155203_users.rb”. The numbers that are in the beginning of the file name is a timestamp and that is followed by an underscore then our table name, “users”. All migrations will have a timestamp at the beginning because all migration names have to be unique. You can not have two migrations with the same name and they also have to run in the order which they were created. This is something nice that Ruby does for us so when we run our migrations they will run in order and we don’t have to worry about numbering them ourselves.
  • Lets create the table for our users.
    class Users < ActiveRecord::Migration
         def change
              create_table "users" do |t|
                   t.string "email"
                   t.string "password_digest"
    
                   t.timestamps
              end
         end
    end
    
  • Above we are saying that we would like to create a table with the name of “users” and it is going to have two columns. The first column is “email” that will take a string input and the second is “password_digest” that also takes a string input. The “t.timestamps” is going to give us “created_at” and “updated_at” columns in our database.
  • Lets run that migration! In the terminal type: “rake db:migrate”Screen Shot 2014-07-28 at 12.10.46 PM
  • You will know if the migration was successful if you see something like the above. The migration will affect our “schema.rb” file. If you open up that file you should see the following: Screen Shot 2014-07-28 at 12.13.25 PM
  • Notice that we don’t see the “t.timestamp” instead we see the “created_at” and “updated_at”.
  • Next lets add some controllers to our application. Controllers are going to determine what a user sees. What if a user does not enter in an email address when signing up? What happens if the user types the confirmation password incorrectly? All that logic will be written inside the controllers.
  • We are going to the following controllers for our app, a “users” controller, “sessions” controller, and “login” controller. We can create these by typing in two commands in the terminal.
  • Type into the terminal: rails g controller nameOfController
  • When you type those commands in you should see: Screen Shot 2014-07-28 at 12.19.17 PM
  • When you go back to Sublime you should see three new files created in the “app/controllers” directory. When you open up these two files you will see that each file has a class that inherits from “ApplicationController”. It also has created three folders that correspond to the controllers.
  • We can now create some “actions” for our controllers.
  • Looking at our user_controller.rb file lets create some actions which are really just Ruby methods.

class UsersController < ApplicationController

     def new
          @user = User.new
     end

     def create
          @user = User.new(user_params)

          if @user.save
                session[:user_id] = @user.id
                redirect_to login_index_path, success: 'Thanks for signing up!'
          else
                flash.now[:error] = "Uh oh something went wrong"
                render "new"
          end
     end

private
     def user_params
          params.require(:user).permit(:email, :password, :password_confirmation)
     end

end

  • Above we have our “UsersController” with two actions. First is is a new user is being created with the “new” action. We are creating a new instance of our “User” class and saving it to an instance variable “@user”.
  • The next action we have is “create”. The first line is that we are creating a new instance of user and we are passing in “user_params” from the bottom of the file. These are called “strong params”. In the latest version of Ruby you have to use strong params. If you want to know more about strong params here is a good resource: rubyonrails.org
  • Then we go into an if/else statement. If the user is saved then we are going to redirect them to the “login_index_path” with a message displaying “Thanks for sign up!”
  • If the user is not saved then we are going to display an error message “Uh oh something went wrong” and render the “new” page.
  • Sessions Controller

class SessionsController < ApplicationController

     def create
          user = User.find_by(email: params[:email])
          if user && user.authenticate(params[:password])
               session[:user_id] = user.id
               flash[:success] = "Thanks for logging in!"
               redirect_to login_index_path
          else
               flash[:error] = "something went wrong..."
               render action: 'new'
          end
     end

     def destroy
         session[:user_id] = nil
         redirect_to log_in_path, :notice => "Logged Out"
     end

end

  • The sessions controller is going to work with if a user has already created then they will be able to go to a page where they only have to enter in their email address and password.
  • The create action is going to see if we can find the user in our database by looking for a matching email.
  • Then we have an if/else statement. This is saying if the user object that we found and the password matches then we are going to set the session id to equal the user’s id. This is how it is possible to make sure that when a user signs in that they can only access their account information. We will also show them a flash message saying “Thanks for logging in” and redirecting them to the index page.
  • If they didn’t put in the correct information then we are going to show them a flash message of “something went wrong…” and render the “new” page.
  •  When a user wants to sign out we are going to use the “destroy” action which will set the “session[:user_id]” to nil. Then they get redirected back to the login page.
  • Here is the application controller:

class ApplicationController < ActionController::Base
     # Prevent CSRF attacks by raising an exception.
     # For APIs, you may want to use :null_session instead.
     protect_from_forgery with: :exception
     add_flash_types :success

     def require_user
          if current_user
               true
          else
               redirect_to log_in_path, notice: "You must be logged in"
          end
      end

      helper_method :current_user

      private

      def current_user
           @current_user ||= User.find(session[:user_id]) if session[:user_id]
      end
end

  • Here we are defining what a “current_user” is.
  • Here is the login controller:

class LoginController < ApplicationController
     before_action :require_user
end

  • Above we are saying that the user has to be logged onto the site before they get access to other pages.
  • We need to now tell our application what to do when a user goes to a certain url. For example if a user goes to our “log_in” path our app is going to read that as “sessions#new” (a new users session), but all the user will see is “log_in” in the url. Here are some basic routes for our app:

Rails.application.routes.draw do

     root :to => "users#new"
     get "log_out" => 'sessions#destroy', :as => "log_out"
     get "log_in" => 'sessions#new', :as => "log_in"
     get "sign_up" => 'users#new', :as => "sign_up"

     resources :users
     resources :sessions
     resources :login
     resources :user_sessions, only: [:new, :create]

end

  • You can think of the routes as a map for our app.
  •  So we have our routes set up, but they don’t really lead anywhere yet. We didn’t work with the views! The four views we are going to create are: new.html.erb (for sessions), new.html.erb (for users), application.html.erb (for menu bar and static parts of the pages), and an index.html.erb for when the user logs into the app (will be in views/login directory).
  • This is for our new.html.erb file for the sessions. This is creating a new users session when they have already created an account.

<h1>Log In</h1>

<%= form_tag sessions_path do %>
      <p>
      <%= label_tag :email %><br />
      <%= text_field_tag :email, params[:email] %>
      </p>
      <p>
      <%= label_tag :password, "password" %><br />
      <%= password_field_tag :password %>
      </p>
      <p class="button"><%= submit_tag %></p>
<% end %>

  • This is going to be for our new.html.erb file for users. Generating a new user.

<h1>Sign Up!</h1>

<%= form_for @user do |f| %>
     <% if @user.errors.any? %>
     <div class="error_message">
          <h2>Form is invalid</h2>
          <ul>
               <% for message in @user.errors.full_messages %>
                    <li><%= message %></li>
               <% end %>
          </ul>
     </div>
<% end %>
<p>
     <%= f.label :email %><br />
     <%= f.text_field :email %>
</p>
<p>
     <%= f.label :password %><br />
     <%= f.password_field :password %>
</p>
<p>
     <%= f.label :password_confirmation %><br />
     <%= f.password_field :password_confirmation %>
</p>
<p class="button"><%= f.submit %></p>
<% end %>

  • Here is the application.html.erb file:

</pre>
<pre><!DOCTYPE html>
<html>
     <head>
          <title>Example logging in!</title>
          <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
          <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
          <%= csrf_meta_tags %>
     </head>
     <body>
          <h1>This is from the application.html.erb file!!! Yaaa!</h1></pre>
<pre>          <div id="user_nav">
               <% if current_user %>
                    <p>Logged in as: <%= current_user.email %></p>
                    <%= link_to "Log out", log_out_path %>
               <% else %>
                    <%= link_to "Sign up", sign_up_path %> or
                    <%= link_to "Log in", log_in_path %>
               <% end %>
          </div></pre>
<pre>     <% flash.each do |name, msg| %>
          <%= content_tag :div, msg, :id => "flash_#{name}" %>
     <% end %>

     <%= yield %></pre>
<pre>     </body>
</html></pre>
<pre>

  • Lastly we need our index.html.erb file which will be in our views/login directory. A user will only be able to see this page if they are logged in.

<h1>Welcome to our Login App</h1>
<div>
     <p>This is where all the amazing information would go!</p>
</div>

  • Almost done!! We want to make sure that the user enters in their email address in a good format. What if a user entered in an email address incorrectly? We want a way to tell them they need to correct what they entered. We do this with the “user.rb” file that is in our app/models directory.
class User < ActiveRecord::Base
     has_secure_password
     validates :email, presence: true,
                       uniqueness: true,
                       format: {
                                with: /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9\.-]+\.[A-Za-z]+\Z/
                       }
     before_save :downcase_email
     def downcase_email
          self.email = email.downcase
     end
end
  • Above we are validating the input for the email a user enters. We are also running a method that will downcase an email address if a user enters in email that has capital letters in it.

Now when you go to your terminal and start your rails server again (rails s), go to your browser and type in “localhost:3000”. You should now see the follow!!

Screen Shot 2014-07-28 at 5.44.32 PM

You can now have people register for your app and log into their account!