Ruby on Rails 6 Complete Beginners Course [2020] | David Battersby | Skillshare

Ruby on Rails 6 Complete Beginners Course [2020]

David Battersby, 10+ Years in Full Stack Web Development

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
54 Lessons (3h 26m)
    • 1. Install Brew

      1:57
    • 2. Install RBENV, Ruby and Postgres

      3:17
    • 3. Install Rails

      3:48
    • 4. New Rails Application

      2:00
    • 5. Intro to Rails Server & Localhost

      2:24
    • 6. Creating our Home Page

      3:49
    • 7. Version Control using Git

      2:21
    • 8. Installing PostgreSQL

      2:34
    • 9. Installing the Postgres gem

      1:53
    • 10. Create Database Schema File

      2:31
    • 11. Generating Rails Scaffolding

      5:20
    • 12. Running our First Database Migration

      1:14
    • 13. Scaffolding - Create / Edit / Destroy

      4:00
    • 14. Scaffolding Pros and Cons

      2:00
    • 15. Generate New Controller

      3:23
    • 16. Adding Controller Actions

      1:16
    • 17. Passing Data to Views

      2:44
    • 18. Using Conditions Within Controllers

      2:14
    • 19. Logging data to the Rails Server

      1:46
    • 20. Adding Redirects to Actions

      3:16
    • 21. Setting Flash Data in Controllers

      4:10
    • 22. Using Before Filters

      3:09
    • 23. Destroy Controller from Command Line

      2:06
    • 24. Cleaning Up Our Posts Controller

      3:34
    • 25. Views Folder Structure and File Types

      5:26
    • 26. Bootstrap and Creating our First Partial

      4:24
    • 27. Displaying Post Entries

      7:48
    • 28. Adding Page Navigation to Views

      8:46
    • 29. Partials and Local Variables

      3:21
    • 30. Using yield and content_for in Layouts

      4:28
    • 31. Common Mistakes in Views

      2:09
    • 32. Styling the Homepage View

      8:05
    • 33. Generate a New Rails Model

      1:43
    • 34. ActiveRecord Validations

      5:17
    • 35. Adding a New Model Method

      2:30
    • 36. Class Method vs Instance Methods

      3:49
    • 37. Active Record Associations

      12:00
    • 38. Active Record Callbacks

      8:18
    • 39. Scopes and Scope Chaining

      3:48
    • 40. Rails Console and Sandbox Mode

      2:00
    • 41. Active Record Queries

      6:18
    • 42. Creating New Entries from Rails Console

      3:05
    • 43. Edit and Destroy Database Entries from Rails Console

      4:30
    • 44. Asset Pipline, Webpacker and Yarn

      4:35
    • 45. Images and Asset Urls

      5:01
    • 46. Custom Helpers and Views

      5:16
    • 47. Creating Custom Forms

      8:16
    • 48. Custom JS and Remote Forms

      4:20
    • 49. Data Formats and Strong Params

      4:29
    • 50. Form Validation in Views

      2:40
    • 51. Creating a New Database Migration

      1:30
    • 52. Add and Remove Database Columns

      1:55
    • 53. Renaming Database Tables and Columns

      1:55
    • 54. Rolling Back a Rails Migration

      1:18

About This Class

The only up to date course you will find on Ruby on Rails in 2020.

Ruby on Rails is one of the most powerful frameworks for building web applications and is trusted by huge companies such as Airbnb, Twitter, Shopify and Github.

One of the most attractive benefits you will discover with Rails is the ability to create working products FAST! This is why it has been hugely popular with many startups and a highly sought after skillset in tech hubs like Silicon Valley.

The underlying language for Rails is Ruby. Ruby was created for developer satisfaction, with the language being very easy to learn and lightweight in comparison to many other verbose languages and frameworks.

Ruby on Rails has changed a lot since the earlier versions and Rails 6 is no exception. Throughout this course we will focus on learning all the basics to get you comfortable building any Rails app you can imagine in the latest framework.

Transcripts

1. Install Brew: welcome to the first video in our Siris. In this section, we will be focusing on setting up our local working environment. So we will be installing Ruby. We'll be installing Ruby on rails. We'll be setting up our database so the set up videos will be focused on using Mac. If you're on a different operating systems such as windows, are you bun to? You can check out the resources at the end of this section, which will tell you how to set up for those other operating systems. So let's begin by instilling Homebrew. So Homebrew is a package manager for Mac operating systems and you're gonna visit the website at BRU Dog S H. So I'm going to copy this line of text, so we will open up the terminal application. Now you can get that under the lunch pad that is type in terminal and you will get this application So we will be using terminal a lot in this course. So that's something that we will become more familiar with as we progress through the course. Once we paste in this line of text on head to return key, the script will go ahead and download all of the requirements that it has, so it will download the command line tools for X Code on it will download a whole bunch of different modules that it means to get homebrew set up correctly. So when you're running this script, it may take a few minutes for it to complete. So I skipped over some of it here just to keep the video moving on. So you don't have to watch me download all the modules, has a comtech quite some time, so it could take up to five minutes or more to download all of the files, depending on the speed of your Internet connection. So hopefully when you're download's complete, there will be no errors. So are you off? Homebrew will be very simple in these videos. But if you want to learn more about homebrew, you can check out the website Dark star brood on S H, where you can read more about how to use homebrew 2. Install RBENV, Ruby and Postgres: So now that we have homebrew installed, we can use homebrew to install R B E N V. So this is a version manager for Ruby. So we'll run brew and still R b E N V will pass in ruby hyphen build. So once we hit return, this will install some libraries. So the purpose for having a ruby version manager is that it allows us to and still multiple versions of Ruby and we can switch between those versions for different projects as we need them. So now this has bean installed. So now we can use our B E N V in our command line on. We're going to useless to install a version off Ruby. So in this case, I'm going to install version 2.6 point three now. This isn't the latest version, but it is a version I'm using a lot at the moment. The most recent version, I think at the moment is 2.7 point zero. It's up to you what version you use, but I'm going to be using this version for the rest of the course, and in general, there's not too much difference between the version number off Ruby. So between 2.6 and 2.7, there will not be that many changes. So I'm gonna hit the return key on, will download this version of Ruby, and it will take you a few minutes to download this version of Ruby. But for the sake of this video, we will skip over some off waiting time that's involved. So once the installation is complete, we can type R B E N V, and we will pass in a global, and we'll set the global to 2.6 point three. So this is basically just setting the global version of Ruby for us, and now we can type R B E N V space versions. This will list all of the versions on our system so you can see that we have got to be installed correctly. So not one more thing we want to do is install the database post grads so we'll use post grass throughout this course. So this will be our database off choice now by default, Rails comes with sequel light, so sequel light stores the database information in a file, and it's not really ideal for working in production So when we work offline on the production, we use post GREss how you can use my sequel. But for this course, that focus will be using post graze. So if you're on Mac, we will go to the website Post grads app dot com. We will download the latest version off the Post Press, so level download on installation file will open that up and move our post right up until the application's folder. So once you restart your computer, the post pressed apple start automatically. Once it's stolen, you will see a small icon at the top right of your screen. I'm probably the best part about the Post Grass Up is that you don't really need to do any configuring. It just works straight out of the box. 3. Install Rails: So in the previous video, we set up the R B e N V on One thing we still need to do on that is to add it to our bash profile. So what that means is, once we use terminal, once we open new terminal window, we want our We want our version manager for Ruby to load automatically so we can do that by adding it to this final called Bash Profile. Now, if you're on a different version off Micro s, then the process might be slightly different. But there are many resources online that show how to set this up in different operating systems. Pre type R B he envy space global. We can see that we've caught the correct version of Ruby set up a global. But when we check, the active version of Ruby that's running right now is different from let version that we installed. So let's look at how we can fix that now. Every time RB envy Shell, we get a message saying that the shell is not integrated correctly, so I'm going to follow the on screen instructions on run the R B e N V with the initiate Command So this gives us some information this time. So it's saying that we need to add less evil and it to our bash profile. So I will copy the text on we will open up the Bash profile. I'm going to use the built in editor called Nano so we can see the top line is what we input earlier we pasted this in, but we want to include a new line, so I'm typing this in right now, but you can just paste this in. So this line of code will allow us to run the R B E N V. Once he opened a new terminal window, so will automatically load the version of Ruby that we have selected. So even though we've added this code to our bash profile, we haven't actually loaded that bash profile again. So in order to do that will open a new tab which should refresh our version of Ruby on now . Once we run the version, Ruby, we can see that it is the version that we have added, so that's working now. So the next step will be to still rails, so we'll do that using Ruby itself. So we can use the jam install rails on will pass and a version number off 6.0 point 2.1. And this will run for a few minutes before all of the dependencies are pulled down. So rails will require a bunch of different libraries to run correctly. So now that this is complete, the next step I will take is to create a new directory. We'll call it directory sites, and this directory will contain our ruby on rails, applications and any other websites that we have. So now I will change directory into this Sites folder. So the last command that we will type is R B E N V, and we will type rehash. So this will refresh the settings on. It will allow us to detect the version off rails that we have just installed. So now let's check the version of rails on. We'll see that we have got the latest 6.0 point to buy one. So now that we have rails installed, we are ready to begin creating our first application 4. New Rails Application: In this video, we will be creating our first rails application on if we open up terminal and we use the rails New command. We can create a new ruby on rails application, but before we do that, we can pass in this help parameter will be added to hyphens on the word help. We can get a list off some of the different options that are available when we are creating a new application so we can pass in things such as the type of database we want to use. We can also skip a lot of different features that are built into rails by default. When we create a new application, we need to use the rails new command, and then we pass in the name off the application that we want to create. And if we try to run it without the application name. Rails does not know where to put our new files, so it will prompt us to add the app path. And once you run that, we get a lot of different files here created automatically, and you can see here that there is a number off different third party gems being installed now these are set up by default on these are the dependencies that are required to run. Our application on the gym is just 1/3 party plug in, so it's some code that we can use within our application. We will talk more about gems in the future video, but I just wanted to highlight it now so that you have a basic understanding of what is happening here. This whole process, when creating a new application, can take a few minutes, and it really depends on the speed of your Internet connection. If you have Ruby set up correctly on your computer, this should install without any issues. But there are cases when installing rails and creating a new application can become a bit of a problem, and I will try to include some resources in this section to help with any of those issues you may encounter. 5. Intro to Rails Server & Localhost: by this point, we have our ruby on rails application installed. If we run the L s command in the terminal, we can see that we have this new folder called Rails Up. So once we create application, it creates the folder based on the name that you pass in. So we'll move into that application folder on we're gonna open this folder using our atom code editor. So if you're not using Adam, you can open this folder within whichever code editor that you want to use on. Once we have an open we can see on the left side, you got all these different folders that have been set up for us. So as part of the rails framework, he craved his folder structure so that it's very easy for us to know where to put our code . In order to get our application running, we return to the terminal on we will use the command rails. Server real server will run our application for us, and we can also shorten this command two rails s. I normally like to use the shortened version as it's just easier less to type once we are starting our server as you can see once we've run the rails server gun, get this information about our application that it is running rail six. So we can also see that we're running in development mode. We can access our application and the browser by running local host on by Default Rails uses a port 3000 on. Then in the browser, we can see that we are running rails. 6.0 point 2.1 on our ruby version is 2.6 point three. Another useful thing about the rail server is that it allows us to see the server logs as we access our application. So I've reloaded the page here a few times, and you can see all of the different entries for each request, so this could be helpful later, when we want to debug our application. The rail server is the best place to be checking to see what is happening with our application. And then finally, once we want to stop our real server, we can do that by using the control plus C. So by pressing control and see at the same time, we can cancel out off the rails. Server 6. Creating our Home Page: So let's start our rail server once more on the next thing we're going to do is set up a customized home page. So in order to do this, we need to open up our can think folder within the rails app that we have created. And within this folder you will find a file called routes dot R B. So all of the U RL's that are used within our application will be defined here within this routes file when defining a home page in the routes file. It should be the last line off this file before we close the and tack. So this will be the default route for application. So in order to define the home page, we need to usually route to syntax. And then we have the name of the controller and the first part of the string. So as public controller, and then we have a hashtag followed by the index or the method within that controller. So in this case, we're calling that homepage. Eso will be using the public controller and having the action off homepage on. In order to get this working, we will need to create a new controller now we won't go too deep into controllers and this section of the course, but I will just show briefly how to get this working for the home page. So we will need to create a new file and list controllers folder. On the format will be the name of the controller, followed by an underscore. And in the World Controller and all controller files are Ruby Files. So the final type must be don't RB at the end, and our new public controller will inherit from that application controller. Don't worry if you feel a little bit lost here at the moment, this will start to make more sense when we cover it in greater detail in the controller section of the course. So now let's define our home page method. So when used inside a controller, thes are often referred to as a action these blocks of code so consolidating method or action. But what this does is it calls the view from within the views folder, app, fuse. Onda should have a folder in here that matches the name off that controller. So in this case will call it public and then was in the public folder by default. This home page method will try to call a file called Home Page, so we'll try to render a file called Home Page so that's create to file for it to load and will use the file extension dot html dot e. R. B. So Don t R B allows us to have ruby code in this file. So this is the default template ing engine that we can use and rails, but there are other template ing engines we can use to, but for simplicity, we will start with html dot trb and we're just gonna add some text here just to test that this file is being looted correctly. So now we can go back to our browser and if we reload, the page should be getting our new homepage. Most of the concept we discussed in this video will be covered in greater detail later in the course where we have individual sections on setting up views, routes and controllers. We are just trying to get everything set up in a very simple way to demonstrate how to create a home page 7. Version Control using Git: in this video. I want to talk about using version control in our application, and this is more of a optional part off the course. You can actually build Web applications without using git. But get makes it easier for us to deploy our application once it is ready to put online. And it also allows us to store the changes we made to our code and roll those back at any point in time. So we have this dot get folder in our application by default on the left side of the window , you can see that all of these files are green by default. All of these files have bean modified or not checked into the version control system. And if we go to our terminal window, I'm going to open a new tab here in terminal. And if I type get status, you can see that there are a lot of files here that are ready to be committed to our repository. And you also noticed that there is a dot get ignore file in our rails up directory on by default. April already ignore our database files on our temp files, log files on quite a number of other files that we will commonly use within rails. So he's already ignored by get And you can add your own entries to this file if there are certain files who do not want to commit to your get repository so within the atom editor, these files will show up in green if they have not being added to our get repository yet. So in order to remove this green color, the quick way for me to do that is just commit these files to our repository. I'm showing you how to do that. Now, if you're not already familiar with that, we just get add all the files and we will commit those files. And now, once we do get status, everything is up to date. If you're not already familiar with get, I do encourage you to check out the website on follow some basic tutorials on how to get up and running with git, as we will be using it later in this course to deploy our code to the cloud 8. Installing PostgreSQL: in this video, we are going to look at how we can install a different database type for our application. Now, in this case, I want to install Post Prez Now. If you're on a Mac, you can. It stole the post crap by visiting postcards app dot com. And then you just need to download the application and move it into the application's folder. Andi controlled the on screen instructions to get this set up, but it's fairly easy, and this is how I have disgraced configured on my own system. I want you have the application installed. You will see an icon at the top off your screen. Andi, as you can see here that I have postcards open right now that is running. Urgent 9.6. If you click on the Open Post Grads link, we can see different databases I already have installed by default this post cross apple start at runtime. So if you restart your computer, this post grads application will be running automatically. Once you have the Post Grads application installed, we will open up the file under config under its a file here called database dot Why am L and within this file. We want to change the adapter. So at the top section of this file, you can see a default this off settings. And then there is a development test on production settings so you can define the settings for each, please different environments. But they all inherit from this list off default settings. So, ideally, we want to keep the same type of database for every environment. That way we can detect any problems before you put them life. So in this case, we will update the adapter and the default section had said it to post grads que el and I'm gonna remove the sequel like three extension for each think databases. We can add a description to the front of this database name. Since I have multiple applications on my local machine so we can call this rails. Blawg notes copy and paste that into each of the different environments 9. Installing the Postgres gem: So now that we have the Post grad app downloaded on, we have changed our configuration settings. We want to install the post Crest Jam. We can do this by searching on Google for the Post Grads jam On the top result will give us this gem called PG. On the right side of the page, we will see details how to include this gem in our rails project. So we want to copy this code on pasted into a file called JEM File. So this is at the root directory off our application. We'll open this file. We will comment out this sequel Light three. Jim, we can just comment that out because we're not going to be using that for our database Well paced in the new gem, our post grass. And we can add a comment here, too, just to say that this is a post credit data bees. And if this is the first time you have seen are used a jam and ruby and try not to worry too much about this, it will become very familiar to you as we progress through the course. Now, when it comes to installing a jam and Ruby on rails. We use the bundle and stole command in the terminal. So that will check against our gem file. Andi stole anything that is listed within that jam file. So in this case, we are getting the latest version off. RPG, Jim. So now that that has installed become cancel out off the rail server, we can cancel that out. Using the control. See Andi? Then we are ready to start the server again on use our new gym. 10. Create Database Schema File: in this video, we want to finalize setting up our database now in our APP directory. If we look at the DB folder, you will see here that by default there is a sequel light file, and we can safely remove that now, since we're not using sequel light. But there's also one more file here called seeds Thought RB on in. Here is where we would put code to generate database entries just to start off a new application That way that if you share your application with other developers, they can quickly replicate the database injuries that you have in your local environment. So now we will go ahead and create our database when setting up a database just like most things and ruby on rails, we will be using the terminal to carry out the creation off the database. So we'll type in the command rails DB, and we'll use a cool on and we will say, create rails, TV create. And if you go back to our database file, we can see here that this will be creating not only a development database but also a test database. So both off these databases have been created now on. If we were to look into the post grads up, we would find those databases in there already. So the next thing we will do is create a schema file for database. So in order to do that, we will do rails db migrate from the terminal. So the schema file allows us to see the version off the database that were on on. It will outline for us all off the tables that are in our database on the columns within those tables. So the schema file is a great place to see the structure off the data that is in your database. Once you run this command, we will see a new file created and the DB folder and you will see now a scheme and RB file . So that's open this up on in here, we will see a version number off zero. So I haven't run any migrations yet, but we have just created this file so later. Once we cover the database migrations section of this course, you will see that this version number increases every time we run a new migration 11. Generating Rails Scaffolding: in this video, we'll be looking at scaffolding on scaffolding is really useful for generating the boilerplate code we need to create entries in our database. So in this case we're using terminal on, we will type rails, generate we can use the rails, generate to create controllers models and, in this case, scaffolding. So we'll type the command rails, generate scaffold well, but the singular name off what we're creating in this case, we want to create posts so we'll just do the singular, which is post with an uppercase letter at the beginning of the word on. Then we can add the field names or column names that we want in our database table, so we want to include the title, which will be a string of text. We will also include a summary column, and that will be a string also, and then finally, we will include a body column, which will be a larger text field. And just to make it more interesting, we conclude a additional field with a different column type. In this case, we will call it active, and we'll make that 1,000,000,000 value so it will be a true or false value so the 1,000,000,000 value will be whether we see that log post on the front end of the website or not. So let's look at the files that being created once we run this command. So the first file is a database migration file, and we have a model some test unit files on a resources path in our routes file. We also have a controller or the posts and some new views and see the Views Posts folder has been created different files in there. On we have various other files here, including J builder helpers test units on and also some style sheets that have been created under the Assets Folder. So there's some of these files that we do not need and we can remove. But many of these files are very useful to get us up and running very quickly. So one file that gets created by default his scaffolds dot s E. S s. So the scaffold style sheet will be created by default on In general. I don't like this file because the styling is a little bit ugly, so it's up to yourself. You can keep this, but I generally just take this out because I don't think it's very attractive on the front end. I'm gonna delete this file, but again, is optional this step. So we have got this new posts style sheet on in here. You will get some information about how it gets included in the application CSS. So if you go to the application dot CSS file, you will see here that there is a required tree command and what that means is, well, who all off the files within this style sheets holder on then. Finally, there's a require self, so these air rails commands, but the require self will pull in any additional styles in this specific file. This will be included at the end off the application style sheet. Let's have a look at the controller that was created for us. So this is boilerplate code that was created from a scaffold command. So you've got all of the basic crowd features here, so you can create a new post at it existing post on delete Andi. This will give us a good understanding of how the average controller set up on rails. So now let's look at the migration file that has been created So migration files go under this DB Migrate folder on they have a version number, which includes a date on when that migration was created. That's included in the name off the migration. So in here, we can see that is creating a table on the table Name is posts on. Then it will look over this table and insert various fields that we have added via the command line. So it's worth noting that we can actually extend this table and make modifications to it directly from this file. So in this case, I'm gonna modify the 1,000,000,000 value and set a default value off. True what we create a migration generates this file, but we haven't actually published out migration or run that migration against our database yet. So you'll notice here the bottom there is this time stamps entry. And what that does is create two columns in our database table. So these two columns, like I created, are automatically updated when we create an entry, are update that entry. We'll look at those later once we get onto the schema file 12. Running our First Database Migration: So now we need to run this migration and order for it to create a table. So let's go back to the terminal on Will enter rails Devi Cool on my great. So this rails to be migrate will processes file that we have modified Andi, it will generate the table in our database. So now let's go back to the schema file on. You see here that the version number has changed includes the date and the time stamp off when this migration was created and then underneath you will see the Our new table is listed here. We've got this posts table on. We can see all of the different columns that we've created. You also see her at the bottom. We have these two additional daytime combs that comes from the time stamps that we were discussing a few moments ago on these air good toe have, as it allows us to record dates very easily. So this is just one example off the features that rails has built in by default that make our life easier. So in the next video, we will look at using our browser to create, update and delete these entries for this table 13. Scaffolding - Create / Edit / Destroy: in this video, we will be testing out our new posts within the browser. So before we begin, let's look at our routes file within the CONFIG folder and in here you will see the resources posts. So this line is telling our rails application that we want to use a default path for all the basic actions around the posts. So creating a new post, editing and updating an existing post, the leading opposed on everything else. So this line tells rails to create all those past for us for our posts. So let's have a look at this in our consul using rails routes. So this will give us a break down all the routes within our application. So you can see here at the top. We have multiple entries for posts. So you've got quite a few actions here. We have the index have create we have edit, show, update and destroy. So all of these actions are defined from the single line within our routes file. So we can also see the actions within that controller. So the post controller and then on the left side, we can see the verb being used, and that is the type of request they were making when we access each of these routes. So in the case off, just seeing our posts will be using the get request. So that will be slash posts and for editing will be posts slash i d. But this is enough to get us started. So let's go back to our browser now. So based on the information from running rails routes in the terminal, we can see now that we visit the slash posts page and the URL on this will bring us to this template ID page where we can create a new post. You'll see the title, and they looked to be a table here outlining all off the columns in our database. So let's hit the new post and create our first log post in our rails application. So now we can see all of these fields have been created for us all of these farm fields. So these are the columns that we have to find in our database. So that's a title summary. Andi body content. So this farm needs improved in terms of styling, but that's just focus on getting the functionality right first, So it's gonna. But some details in here. Andi, you will notice here that the active is a checkbooks. That's a 1,000,000,000 value on by default. We have said it to be true. So that is checked by default. Now we can see the details of what we have submitted. So the post has been created. Click the back button. Then we will see this post in this table now. So now we can click on the link to the right to edit this post, and you will see here that all of the details are ready in place for us. So let's modify this on. Click the update Post button. I know you could see that the Post has been updated. Click the back button once again, and this time we'll click on the destroy button. We'll get this dialogue pop up. We have to confirm on now it has been destroyed. So now we can see how easy it is to get up and running using the rails scaffold. So in the next video, we'll talk about the pros and cons of using rail scaffolding on when would be the right time to use it in a project 14. Scaffolding Pros and Cons: So let's look at some of the reasons that you may want to use the rail scaffolding. Probably the most useful part of the rail scaffolding is the boilerplate code that it creates, especially around the views on the controllers. But there are a lot of files that get created that we don't necessarily need, such as helpers on task unit files. So you may or may not want to use some of these files, but by default, they're all created for us when we use the scaffolding. However, even though there are a lot of files that we don't necessarily need, I would definitely recommend in the beginning. While you start to learn more about Ruby on rails that you actually make use off scaffolding, I think in the beginning, when you're learning rails, it really helps to understand how the code is placed within the folder structure. So by using the files that get created for us, it already has everything working on. We can simply go ahead and style up the views just to make it better looking on the front end and some of the files that are empty here, like the model for the post this is actually a required file, but it will also allow us to easily add methods within that file. So looking here at the controller, we can see the boilerplate code that was created from the scaffolding on it does everything that we need to. So we've got no the index method which shows all the posts. We've got the new method which shows the forum to create a new entry on Do we have to create on destroying methods? So everything is here already working, and it gives a really good place for us to learn about how things should work and rails in the next section of this course. We will go into more detail about how to use controller modify it on past data to the views . 15. Generate New Controller: in this video, we'll be creating a controller using the rails, generate controller command. And before we do that, this look at what has been created using the scaffolding so between previously we used the rail scaffolding to create controller for posts. But it also creates some additional files that we don't necessarily need. So perhaps we don't need to have a database table or a model. Maybe we just need to controller on the views. So in this case, we would be better creating he controller using the rails generate controller command. So let's try this out. And we will give a name for this controller so we'll call this controller. Welcome on. We will pass, in some words, to define the actions within this controller. So have a home. We'll also have an about page on. We'll have a contact page. So once we submit this, it will generate all of these three files for us for the views, and it will generate a lot of other files along with that. So first here we can see that we've got the controller created Andi. Then there is a route for each of these pages. Andi, Underneath the routes and we have the views. So we got a new folder for views. Have a home about contact Page. So these much the words that we just passed in to this command on then underneath we've got some helper files, test unit test files on some style sheets, so very basic files compared with what was created using the scaffolding. So that's open up a controller now, and you can see that we have got individual actions for each off these pages. Now let's visit the routes. Don't RB file within the CONFIG folder, and you'll see there is a separate line for each of these new actions within our controller , and it's using the get requests. So these are you RL's that we can visit within the Viewers folder. Then we can see each individual file that's been created for us, and it tells you the location of that file. So now that's stop the rails server for a moment and restart it again. It's good to get into the habit of restarting the rail server after you make any major changes to application. So now let's go back to the browser and type in one of the Urals So let's input. Welcome slash home on. You can see, then the output off our view. So this year l much is what is in our routes file. So by now you can probably see the advantage of using the rails generate controller so it saves a lot of time in that set up on it generates a boilerplate code that we need to get up and running very quickly. So it's not too different from the rial scaffolding command, except the main difference between the two is with the rails. Generate controller. We do not actually create any database migrations on. We do not create a model by default, so it's great if you just need to create a controller and some views for static pages. 16. Adding Controller Actions: So once we have a controller created, there may be times when we need to add on additional action to that controller and to add a new action. There is actually no automated way to do this, but we can do it manually on it's very simple. So let's do that now. We'll add a new method or action called features, so this code will look the same as the other actions on this controller. So we'll also need to add a new view within Welcome folder. Call it features dot html dot e r. B So the E R B extension is for on embedded ruby file. So it tells our application that we are creating an HTML page with Ruby inside it. So let's go to our routes file within the CONFIG folder on We will just add another get request on now. You can see when we visit the u R L that the page is working. So that's it is actually quite easy to add a new action to a controller 17. Passing Data to Views: When we look at the action in our controller, we can see that the action is empty. There's no code inside what's actually happening. Behind the scenes is this method or action in the controller will load a page with the same name directly from our Views folder, so it will try to find a folder called Welcome, and then it will load a view called home. We can actually change that by modifying the action. So let's have a look at what's happening behind the scenes. So if we do not tell rails which view we want to load, it will automatically render a view for us. So it will try to find the folder with the same name as the controller on. Then it will find a file with a name off that action. So we'll look a little bit like this will be a render at the bottom off our action, which tells rails what file eluding. And we could modify this ourselves. We can pull in a different view, So in general it makes more sense to do this the rails way by keeping the name off our controller action the same as a view. But just to let you know how it works. Behind the scenes so automatically, even if there's no code inside in action, it will noto load that appropriate view from the Views folder. So let's look at now passing some information to that view. So to do that, we will use an instance variable. So like we covered in the ruby section of the course, an instance variable begins with the alias sign. So anything we but with that alias sign in front of it will be available within our views. That's output that now to the browser. So we can do that using the less land symbol on the percentage sign. So that's to open a block of code within Ruby. Andi will use the equal sign to output that to the screen. We're gonna be printing out this value off the message. Instance variable and we can close off that block of code using the percentage sign on the greater land symbol, and that once we reload the page, you can see at the bottom. We have got this message that has been passed from the controller, So this is an easy way to pass information from the controller to the views on you can create as many instance variables as you need. We can actually assign conditional statements within the controller, which will be doing in the next video to show how you can change that message based on certain parameters. 18. Using Conditions Within Controllers: So let's go back to our controller again. On this time, we're going to add some additional statements here to control the flow off the data. So let's begin by creating a variable. So you'll notice here that we don't have an alias in front of this variable. So we're going to be using this variable Onley within this action will create this variable called some Value on. We will assigning a value of true. And then we will create an if statement to check the value off this variable. So right now, we're checking both the type of the object on the value off that variable. But we can shorten this statement so once we shorten it, we are Onley checking to see if the value is true on if the value is true, Then we will assign a instance variable cold message. I will give it a string of text, Andi, otherwise and if the value of this variable is not true, we will assign a different value to that message. So this is a very simple example, but it will allow us to see quite quickly whether the condition is being mad or not. So once we change the value to fills. You can see a different message in the view. So let's look back at our posts. Controller on here we will see a more common use case for conditional statements in the controller. So probably the most common use case for this is when you're saving data to the database. So in this case, we were saying, if the post dot save, then we can handle some custom redirect or rendering based on the size saved. But if it's not safe, then we can also redirect the user back to the form page. So this is a common example when creating, updating, destroying. So not only does it allow us to control the flow off our code, but it allows us to return a message back to the user to notify them that the action was completed successfully. In the next video, we will take this one step further by logging information to the rails console, and then finally we will redirect the user based on this conditional statement, 19. Logging data to the Rails Server: when you're working with dynamic data, it can be useful to debug that information. Using the rails server on, we can output to the rail server using the rails dot logger so the rail start longer will print a message to the server, So it's really useful for out putting a value of a variable on will test out in this case. So here is a server where we will be out putting, too. So when passing a value to the server logs, we can tailor pass it using the longer dot info, or it can be longer dot debug on. And from my experience, the debug method makes more sense as most of the time. We're trying to debug a variable, so it's out. Put a message on Guy will use string interpolation. So we're out putting our message and since variable within a string of text. So let's have a look at the server logs on here. You can see the message that we're out putting so you can actually shorten this to just longer dlt bug on the site from debug. We can also add various different logging levels, including info error on fatal, but by default I generally used the debug for out putting any information to the rails console. You can actually take this out of the string unjust, directly debug that variable to the rail server. So as you can see debugging values, using the rails longer is quite easy. And that's something we'll find yourself doing a lot as you build rails applications. 20. Adding Redirects to Actions: in this video, we'll be looking at redirecting the user based on conditional. So we have this value already set. So I got this some value. This is a variable. So if there's variable is true, then we can redirect the user to a different page. So in order to redirect, we will use this redirect to help her on. Then we will pass in the U. R L or the path that we want to redirect the user to. And in this case, since we're doing a conditional if the value is not true, we will redirect the user to a different page. So it's worth noting here that we can use both the euro on the path. So in rails, you can choose between the path on the U. R L. And most of the time you can use a path. But the year l is helpful if you're sending emails or something outside of the application . So both of these cases we will be ready redirecting the user. Andi, it looks like we have a table here in our path Name. Now, if you see this, it usually means there's something wrong with the route that you have for this for this view. So let's go and look at our routes. We could do that using the rails routes in the terminal. Onda We will see that the names for our routes are using the controller and the name of the action. So in this case, the features page will be called Welcome underscored features. So we could actually assigned custom names for those in the Routes file, and we'll look at that later in the course. But for now, this just used the name that's been assigned here. So that's working now, and we'll see here that the redirect has already happened. So those changes to true and it should redirect us to the homepage. Now you can see that the euro has changed on the redirect has happened. So in the logs we can also see the redirect. So if you look here at the welcome slash home, it tells us that is redirecting to the local host 3000 and you can see that is a three or to redirect. And then underneath we will see the page that that it gets redirected to which is home page . And there everything looks normal. So a common use case like we mentioned, the other video would be saving a record to the database. So in that case it makes sense to redirect users to different page afterwards. But another common approach is to return information to the user to let them know that the record has been saved the database and we will cover that in the next video by using flash messages. 21. Setting Flash Data in Controllers: in this video will be looking at flash messages, so flash messages are a great way to pass a snippet of information back to the user by other browser. So what normally happens is it is a one time piece of information that after the pages reloaded or the click on or link, they won't see that information again. So it's just a quick way to update the user off what is happening if they are saving a record or they're signing in or signing out to let them know the status off their action. So the flash message can actually be attached directly to the redirect to helper so we can do that using the notice. So there are several other ways that we can write the syntax for this flash message. Normally, we will pass a key in this case. I'm going to give it a key off success. Now it's really up to yourself what you use here, but notice is the default flash key that we would use in rails for me. I like to change this so that we can alter it based on success or failure. So on the front end, then we could style it based. If its success, we could make it green the text, and then if it was danger or fail, we could make the text read so we can easily distinguish between success and failure when carrying out actions in our application. So let's have a look at the application view that's under views. Layout application on. We haven't looked at his file yet, and here is the template data for all of our views. So every request that we make on our application every time we see a front and view it is being output as part of this yield statement. So in here in this template, and we can also add a means to show the flash message we're generating. So to do that, we can use a if statements will say if slash and we'll add the key to our KIIS success and we will have a block of code that gets output if this flash KIIS found. So it's generated paragraph. So let me will output this flash message so I save this file and we will test this out. So let's visit the earl once again. Welcome slash home and now we get this message out put from the flash so Page Redirect was successful, so that is now being out. Put it to the page. So that is working correctly. So going back to our welcome controller, let's have a look at this again, this flash statement because there is a different way that we can write this so we can write this as a separate line. It will cut this text, so if you're writing as a separate line, we can use the square brackets to populate this key, and we will use the equal sign and then passed the value that way. So then, once the redirect happens, it has already stored that flash message. Let's try this once again on the same messages being output. So in the case off this, if statement not being true, then that's returned a different message when redirecting to the features page. So it's changed this value toe falls on. We will visit the page again. On this time, you can see that we have a different message being output to the browser. So this is working correctly on. You can see many different use cases where you can use flash messaging within your application, but it's really quick and easy way to output information back to the user 22. Using Before Filters: in this video, we will be adding a filter on this filter will get called before each action on this controller. So each of these pages are referred to as actions Onda. We can call a before underscore action. So this will be calling a method before each of these actions on you will give this a name , we'll call this set values and we will define that set values at the bottom of our controller. And we'll put this into a private section over controller. So this will only be accessed by other methods within this Controller Onda, we should know here that all off the code called within this method will run before each of the actions. So in this case, I'm going to set a instance variable with a name off David Andi that will be set and before each off the actions on this page. So the contact page about page features page on even the homepage will all receive the value for this name. So I'm going to delete the old code that we had here before on and then we will set this name in the application view it is Open that up views layouts application on the bottom. Off this body tag, it will output the name so that we contested across each action. And here we can introduce a new conditional statement so we can actually have a if statement in the same line as the output. So we can say name if named are present with a question mark that will detect if that name is set that variable set on the opposite off. That is, unless named are present so we can do that right away. But it's just good to have a chicken there to ensure the variable it's set before we try to out put it to the screen. So now when we visit the features page, we can see the name has been added to the end of the page on the same on the contact page and then the same for the home page. So back in our controller again, we can actually limit this method to be set for certain actions. So in this case, we can pass in a constraint called on Lee. On That will be an array which contains the actions that we only want to display this value on. So now once we try to visit, the other pages will see that the name is no longer available because our method has not been run So we can change that constraint to accept on that means it'll display on all of the other pages except for the homepage. So we try this again, contact we're seeing the name features were also saying the name on We go to the home We don't see the name so we can limit the method being cold certain actions within our controller. 23. Destroy Controller from Command Line: in this video, we will be looking at how to remove the controller on all of the files that were created by the rails. Generate controller command Some of the files ago created or helper files. Onda. We had a style sheet file. Andi views on the controller itself. So required number of files created by this command on its very easy to miss them when removing the controller itself. So a good way to do this is to run the command rails, destroy. And then we'll pass the word controller so that it knows the files that were created. Rails destroying controller, and then the name off the controller that we created previously. That is welcome on. Once we run this command, you will see that many many of the files that were created previously have being deleted. So the controllers deleted views folder has Beene deleted. We have a test controller helper on the style sheet. All got removed. Andi. It's just a quick and easy way to clean up the files. And you can see here that this file is still open. But that is not saved anymore. But you can see I've been deleted on now. our views have been taken out. So we used that controller just as a means off learning how to create controller and the actions that contains the one thing to note here is that in the routes file, the entries for our welcome patroller are still here. So these need to be manually deleted. And I guess there are some things that it's just a little bit too risky for rails to trying to leave by itself. Other than that, this is pretty useful command to clean up any controllers or scaffolding that create possibly. If you want to change the name of a scaffolding or something like that, this might be a good way to remove it and start again so we can use out on scaffolding controller models. 24. Cleaning Up Our Posts Controller: So let's go back to our post controller that we created at the beginning off this section. Now you'll see in here that we have this before action. The top, like you are discussing and previous video on it calls this set post method. And here you will see something very familiar throughout most rails projects. So we sat a post within this method. Andi. So that happens before each of these actions get cold to update, to destroy, to show that posed to let is being set from that method, we're going to clean up this controller a little bit just to make things easier to understand, as a code is very verbose at the moment. So one of the things I'm doing here is removing the Jason from each of these actions. So we only want this to be displaying from HTML. So we'll take out this formatting altogether. We'll discuss this more in the different video. We will cover formatting on different format types and rails. But for the sake of this video, we're going to clean this up, keep it very simple to begin with solicitous, remove all of this formatting. And once you remove this you'll start to see that the controller is actually really simple . And that is one of the things that is very appealing about using Ruby. You can create a lot of functionality by writing very little code. So looking at the create action, we can see that a new post is being created post, don't you? On If you open up, this post model will say that we're simply referencing this post. And the don't new is a building method as part of the model, and we'll cover more of models in the next section. But at the moment, all you need to know is that critical new model with parameters. And if you look at the code underneath that and we are simply saying if this post is saved and again this is a built in method is part of the models rails. So if the post is saved, then we simply redirect to that post on. We passed this message as part of a flash message to say that was successfully created, and if it doesn't get created, then we are rendering a action to rending the new action. So that would bring the user back to the forum to correct any mistakes they made, Andi. Then we'll clean up this update. Action also again and removing formatting for now. Take out Jason. What? You remove that the method or the action actually looks really simple in terms off the code , we're gonna go five or six lines of code for this whole method, this whole action and against the user, the ability to update the entry in the data bees. It was pretty good that we can keep it. This symbol, Andi again. Finally, we will just tidy up this destroy method. The destroy method is two lines off code. So that's probably the shortest we can get any of these actions that's really, really small on yet providing the functionality off, being able to destroy a entry in the database. So now our controller is looking much cleaner. Easier to understand. In the next section, we will be having a closer look at views and how to improve the styles on the front end 25. Views Folder Structure and File Types: in this section. Off the course, we will be looking at the views directory. So by default, once we create a new application, we have this layouts folder within the views on everything you see on the front end of a rails Application is coming from the Views folder. So by default we will load the application. Hte email dot e RB file. That's the very first file gets loaded when it comes to the views. So we will begin by cleaning up this file and removing the modifications were made to it in the last section. So once you start a new application, your template code will look a lot like this. So it is a bear Bolan's template in our application. So the top we have a title, which is a name off our app. Onda. We have a style sheet link tag, so this is a link to the compiled style sheet on. We also have a JavaScript tag, so you'll notice here that is a pack tag. JavaScript. Pac files have only been introduced in the most recent versions off ruby on rails, and if you've used an older version off rails, then you will notice that the JAVASCRIPT folder has moved outside of the asset directory. So the pack tag is located under the Pax folder within JavaScript. Andi in here, we use require statements to load the JavaScript, which gets compiled into a single file. So we'll talk about more about JavaScript in a leader video. But for now, we're just highlighting some of these things that we will see within the views. So next we have the mailer file. This is the template layout for our emails, and we also have a text only version of the email. So now let's look at the posts. Directory on. Everything in here was created by the scaffolding. The rails generates scaffolding. So you'll notice here that there are some J builder files on what they are is simply a Jason response off the data that come in spite from our database. So in our case, these are good to have a look at, but we don't really need them for our application. So one of the reasons I think that they are part all of the scaffold is really so that we can learn how to place our code within the application, so they're useful to understand the concept off having Jason data here, but for most purposes, we do not need them on the camp removed. So I'm gonna go ahead and remove the J Builder files from this directory. And now let's open up our index file and we'll look at some of the code in here to understand what is happening. So we'll see here at the top. There is a heading headed one tag. So this is the name of our controller on our model. Andi In here on the table header. We have a list of all the columns that we have in our database table and then on the table body underneath were simply showing the title summary all the column values on ability to edit or destroy this entry. And then finally, at the bottom, we have a link tag to create a new post, so we'll go over at least things in more detail. And if your moments but this have a look at the new post now on in the new post, you can see we're rendering a form. We're passing a value off post. So this is a reusable piece of code you can render the form on multiple views. So again, we'll look back at these and more detail as you progress through this section. So then, in the Edit post, we're seeing the render form again, and we have some links on in the show view. Then we output some values that are found on that post out putting the title of summary body and then within the form, we can see the fields that we are populating. So each of the column names are here with a text area field or a text field. So now let's go back to our home page. So on the home page, we want to output some entries from our database, so we want to output the posts that we have created. But before we do that, let's create a new style sheet and then rails. You can use a standard CSS file, or you can use a SAS style. She so they're almost the same, but assessed that she allows us to have a little bit more functionality that allows us to and band styles within other styles on this will contain the styles that we use for our home page and foreign allegation and if you want to learn more about sass and check out the website SAS hyphen. L AMG dot com on DIT will tell you a lot more about what you can do. Using the SAS language that was almost identical to CSS was quite easy to learn. But there are some cool features, like variables, nesting off styles. Now, generally, I only use as in a very basic way, so most of what I do in this course with fast will be very easy for you to follow. 26. Bootstrap and Creating our First Partial: in order to improve the look and feel off, our front end in our application will be installing Bootstrap Onda. We will install this using the Cdn links, but you are ails that are available. So there are multiple ways to instill libraries in ruby on rails applications. But since this is a beginner course, we will take the easier option off, using the you're ales and dropping them into our template. So part of boots drop requirements is to install J Query on proper Js. So we give us links to drop into our application so it's add does to the bottom off the body. So we're adding this code into our application layout within the Views Layouts folder. And in fact, this might be a good time to introduce using a partial. So a partial in rails begins with an underscore and the file name on partials have the same properties as views slowly and in a html dot e. R B extension. Partials also make it easier for us to keep our code clean, and the most important property off partials is that it allows us to use the code in multiple locations. We can use the same partial across multiple views. On that way, we're not repeating the code and multiple places when you want to include a partial. In your view, we do that using the render helper, we say render partial colon and then we input the path to that partial will be inside the layouts folder on the partial is called Food er It was closed like health, and that will include are partial inside off this template. So once I look at the source code bottom of the page, we can see the script has been included. The partial is loading correctly and while we're looking at the source code, you can also see her at the top. Each of these style sheets are being output individually. Alice Onley happens in the development environment. Off rails, once is is in production. This will all be combined into one style sheet and you can see here that the JavaScript file has been compiled for us on is only chewing one style above this, you can see a sea SRF token. And the purpose of this is for security in our application. So this is set by default in the application lee out. So Now there's copy remaining tags for our bootstrap couple these on. Drop them into our and plead so I will paste this code inside the had tag off the page. I'm gonna take this JavaScript final, and we'll move it to the bottom off the page, including it in the partial that will be last to be loaded. That is the bootstrap JavaScript file. So now let's add some mark up to our application layout to test if bootstrap has been installed correctly. So by adding a container class on a row, and we will finally add a column inside that road. So what we're trying to do here is create a maximum width to the page and there should be some margin on the outside the page. Let's move our yields statement into this markup. So in our home page, then we will just have some dummy text and we'll test this out on the browser. We could see the guys working. The content has been pushed in from the outside of the browser, so this is a normally out for bootstrap, so it looks like everything's working so far 27. Displaying Post Entries: in this video, we will be out putting the entries from our database onto our home page. So let's have a look at how we can populate data from our controller. So on the home page, we will create a heading tag with latest posts on. We're gonna iterating over a instance variable containing our posts. So before we do that, let's just remind ourselves off the columns in our database. We can visit the DB folder and open up the schema file. So in here, we've got the title tag, which is the string on the summary is also a string. And along with those, we will want to include a link to the Post which will give us more details. So in our home page view, it will output summary of each post with a link for more details. So in order to get that data, we need to go to our public controller, Andi In the homepage section, we will pull in the data from the database. We'll create an instance variable called posts, and we will load the post model and we're going to use the selector for all off the entries , which is all so If you look at the post model here, what we're really doing is just loading the reference to this model on will use a keyword all to select all of the entries that are part off that database table. So back in our home page view that's open our ruby command on. We're going to reiterate over the posts. Instance variable. So we will say posts dot each do on. Then we will pass into these pipes The item name for Latin array. So what Cola Item Post? So that's the current item in the array. While we live over that ray, it's close this tag with the end tag. So now we want to output the title off this post. We'll use a H three tag, no SE post title, and then underneath we will output the post dot summary, and that will be within a paragraph tag. So let's go back to our browser now. Reload the page and you'll see it that we do not have any posts at the moment on. The reason for that is he deleted the last post that we had, so let's go back in here on creating your post. We'll add some dummy information. So now once we click the create post button, it will take us to the show of you. So we will see all the details off this post. Let's create one more post so that we can see how they look. Once they are stacked, we'll be showing more than one post on the home page. So again, that's just add some really basic details for this post. Now let's go back to our home page, and we can see now that our posts have been displayed on the home page, we have the title on the summary text underneath. So now let's try to improve this by adding a link to the title. So we're going to use a link to help her here. So the word link underscore to, and the first value that we passed into. This is what will be shown on screen. So in this case, we can keep the post op title. The second value will need to be the URL or the path on which this lingual point to. So the post underscore path. It's what we are looking for again. If you had a different model, name would put that model name followed by the underscore path and within brackets. Symbol pass in the post on rails will figure out how to create this Ural for us, based on the i d off the post. But now, once we reload the page, we can see that the links are working and you can see at the top is posts slash two. So the idea is in the U. R L. It's on this page. We can see we've got the template data being output to the screen. So this is a dummy template data that is created using the scaffold command in the earlier section. So now let's go to our show view within the posts folder on We will update this to make it look better. So I'm going to delete most of this boilerplate code and in fact, we won't need this summary. Since we have it on the home page, we will want to keep the title on the body and we can delete these links at the bottom. We can remove this notice this flash message at the top. We can add a html heading tag. We'll put our title inside of that. So it's test this out and once we reload the page, we can see the title and we can also see the body text. I was worth noting here that we're only out putting one line in the body text, but if we were to have a multi line text, then there will be an issue displaying it in this way. So if we look at the source here, we can see there are no HTML tags for this text, so we would want that wrapped in a paragraph tag. So does edit that post and see how this looks without modifying our markup. So now we can see all of the text is on the same line. So in order for us to display this correctly, we can use a helper called Simple Format. So that's simple. Format will break this into part a graft tags. So it's reload, and now our content is looking much better. And if we look at the source of the page now, we can see that each line has a separate paragraph 28. Adding Page Navigation to Views: in this video, we will be adding a custom navigation to our layouts. So right now on our up, we have no easy way to get around the different pages. So that's add a navigation menu. So within our application view under layouts, we will render a view here at the top. So this render will contain the code for our navigation, and I want to show you how this works without including a partial. We can call this in the same way that we do with the partial well, but the path in will be layout slash menu. Let's create this new file, and you'll notice here that I am using a underscore at the beginning off the name. So by starting the name with an underscore, we are declaring this file as a partial. So you will see in a render tag we have not declared as a partial, but it's still loads the file anyway, So if you forget to label it correctly, will not break your application. But it is good to use the correct syntax. So back in our partial, let's begin by adding a a Nordic list tag. So at some HTML markup to this navigation on going to add a class here called list unstylish so that class is already defined as part off bootstrap, and it basically just removes the bullet point from the list items. We'll include a link back to the home page and will create a new page for the Blawg and about page on day contact page. So here we can see that our menu is being displayed. However, we do want to have this in line, so I'm going to add an i D. A tribute to this list so we'll give it an I D off top mouth. So now let's go to our public style sheet. We'll create a new style for the top path. So for each list item within this list, you will display in line that makes the navigation horizontal. So now let's go back to our application layout. We want our menu to be in line with body content, so that's create and, you know, within this container, I will also create a new column name. It would move this partial into the colon, so that should build things and lying now, and we can see it has moved directly above the page content. Tonight, let's add a site title. So I want to put a heading one tag at the very top of our page. This will be on the left side and we'll call this rails Blawg. So this will just be the title of our website. So this is a bootstrap class again on it will simply float content to the left of the page and then for the UN ordered list tag. We will also flute that one, but that will go to the right of the page. So now once we reload the page, you can see the title off the site on. We see our menu on the right side of the page and we could still improve this further. So the first thing we can do here is hot a link to help her tag. So the text going into that link will be home on the second parameter will be. The path toward that link is pointing. So in this case, we will use the route path to go to the home page so I can see that the link is not working . So let's go back to our list and we will include a link for each of the remaining pages. So we haven't set these links up yet, but we will just add them and we will go back to our routes file afterwards to create those routes for those pages. So this will be about path. So the name will be about for this page. I will do the same with the blood page. Linked to text is Blawg. And it would be a bloke Underscore path and finally for the contact. We'll do that once again. So now let's go to our routes File config route store, R B and hero create routes for each of these pages. So the verb for this route is GATT, So that will be a get request, which means that is a link that we can visit in our browser on the controller name will be public on the action name will be about. We can also add a name to this path so it can, usually as this will be called log. We put the cooling in front or create ISS for each of the pages. So we have one route for each of these pages now. So it's defined each page within the controller at new action for each piece pages. Once this action gets called, it will try to load a view with the same name. So we do have one issue here. It looks like we forgot something in our route. Let's go back to our routes and fix it. So in a rows file, we are pointing each of these entries toe Republican troller on the action. But we haven't really declared what the u R l will look like. So when we name our out like this, Rails does not know what the u R l should be. We have to define the U. R. L first. In this case, we will set the your L to about for the about page. So b slash about on the same for blawg and in for the contact will be slashed contact. So we use this equals greater land symbol to assign the your l to this controller and action combination. So now this is working. Each of the links are appearing, but this look again at our routes. So in here we have a shorthand format. So we have sign the euro. Using this equals greater land symbol But we could also do this name or descriptive way so we could actually pass the controller name on the the action name. So that way it be very easy for anyone to see what is happening, and it will work just the same way. So it is a bit more verbose, but I think it's a little bit more clear. But if you're used to working with rails, you can write the shorthand way as it will save you a lot of time. So let's look at this as about so we're naming this route about. And if you come here to the U. R. L, you'll see the euro is using about underscore path. So whatever we name at your l, we can replace it in our link, so blawg will be blown. Underscore path contact will be contact underscore path. So the name we give here defines How are your l looks in our templates 29. Partials and Local Variables: So looking back at our home page view this time, we want to make use of a partial. So currently, at the moment we are iterating over this code within our view. But it would be good to put this within a partials who we can reuse it again later. So there are multiple ways to do this. We could move all of this posts, thought each lip inside off the partial, or we could iterating over the loop. Andi, use a partial with in the loop. We're going to do the latter here, going to put the partial within the loop and the partial will output the code for one single post. We are rendering a partial that will be located within the Post folder on the name of that partial will be post. So now, in our partial were still referencing the post onda. We need to actually pass that post value in even though we have set the post in this lip, it's not directly accessible to the partial unless we pass it into the partial and you can see the error is telling us that there is undefined local variable. So if you see that this will give you an idea off What could possibly be wrong? So, looking at the application trace, you can actually look back and see what files have been called. In order to get to this error, you can track down what has went wrong. So this would have worked if we were using a instance Variable. But since we're using a local variable called Post, we need to explicitly pass that into our partial. So let's go back and fix this now. So before we add that variable, let's go back to our partial and have a look at how we can detect if that value has been set or not. So within a partial, we can check to see if a variable is set using Lee local assigns on, we pass in a key off that name. So this time we're saying if local assigns post, then we will execute this code. I'm include off this block of code, so if the post is not available, then there should be no error, and we can see that now. This is working, but we're not getting our posts. So in order to actually show the posts we need to pass in a local variable to the partial. So we can do that using the locals option on the render partial on them within the curly braces. We will set the post and we will assign a value off post. We're assigning that local variable two of the new variable called Post. So now we can see that it is working and we can safely remove this local signs from our partial so you could keep that there. But I was really just showing it to allow us to understand how to detect variables within partials. So in this case, we can change this variable name to anything we like. Also we have to do is change the value of that name. Here we change that named X. This should work just fine and we can see let it is still working. But it does make more sense to keep the name descriptive. 30. Using yield and content_for in Layouts: There are times when we are creating views that we need to pass information back to the application layout. And there's a great way to do this, using a helper called Content for On One example of why you might need to do this is in the title off the page. So each page we go to in our application each page revisit. We will have a different page name based on what that page is about. So in this case, we can update that page title directly from the view itself. So let's look at how we can do that. We can set a content for value. I will set a key for that content, for we'll call this page title on. We will assign it a value. So since we're on the home page, we will assign it value off home, Andi. Then within the title, we want to output that value, using the yield tyke to a pass in the page title to this yield. And now, if you go back to our browser so we can see the name off the page in the tab off our browser window, must we visit the about page there is no title set. So what we can do here is have a in line conditional statement to check to see if that value has been set for the page title on If it's been set, then we will yield the output. This just format this a little bit to make it more clear. So we're checking to see if the content for page title is present on then. Otherwise, we will yield this output to lead this colon. So if the page title is not present, then we will default. Value to Ruby on rails. Plug. So now once we update the page, we can see that the title has changed for the about page. It's got the default title and we've also got the default title on the Blawg. I want to visit the home page. We're getting the correct title. Then we can Kobe this I'm moving into each off the other files to give them a proper name. What changes to Blawg? Must we hit the block page? Agencia. The title is now being updated, so let's look at how we can use the content for as a block instead off in line. So this time will create a script block for the content for on the purpose of list will be to output JavaScript files and any third party files at the bottom off our layout file. So in here we convert anything we want any markup or links or text that we want just to be out. But the bottom off the file for the purpose really of this would be for JavaScript files that only need rendered on this page. But just to give you an idea of how this works, we're going to use a string of text. Let's go back to our application layout. So here at the bottom off our layout pile, we will output the content for block. We will do that using the yield tag again. So it's the key off scripts. And this time I'm going to say, if content for on check, to see if that content for a set before we output it. So we're on the bloke page right now, and if we check the source, you will see that there is no text here. But we've only said this on the home page. So once we go the home page, you will see this text already and again. We could look at the source code on See that Indeed it is at the bottom of the page. So this is a nice weight and Truell the information that could present it to the front end . 31. Common Mistakes in Views: in this video, we will look at a very common problem you will find when dealing with fuse. It was very easy to forget to create a view once you set up the route on the page. So if that's the case, this is a kind of error you will see. Once you click on a link to that page, we're gonna click on the about link. We have this message saying No template for interactive request on the message below is really helpful. Actually, it says public controller about is missing a template for request format and the former is text html. So what is looking for? Here is a about html file, so html don't you RB file It's looking inside the public folder for this file, so there's even more descriptive information underneath this. So if we look inside the controller, you will see that we have got the actions already set up. But once we look inside the views Public folder, there is only one HTML that ye RB file here, and that is for the home page. We need to create new files here for each of these actions. Let's just add a heading tag will output some Lauren hips and text. So just some dummy text to fill the page, so I'll copy this text on it will do the same thing for a log page long. It's time l dot e. R. B. We'll just change the title and we'll do the same for a contact page. So the error message goes away once we read off the page and everything is back to normal. So this is a fairly common error that you will see when you're building applications. 32. Styling the Homepage View: in this video, we will focus on tidying up our views to make this a little bit more presentable on the front end. So functionality wise, everything on the front end is working. Right now. We want to style list to make it a little bit better in terms off design. So let's go back to our style sheet. Open up the public style sheet. We will begin by adding some padding to the top navigation. We'll have a five pixel parting on the top and bottom eight pixel on the left and right. I can adjust this a little bit. I will also add a margin to the top off this list. So a 10 pixel margin. Now let's look at the I always look at the site title. So could this rails Blawg text at the top, but it is really large. So there's control the styling off that well, given I d off site name, then we'll set a fund size except this to 22 pixels. Also, add a top margin. Give some space top of the page. So let's add a way to style this top section of the page. So right now we have this wrapped in a column class. So add another class to this called page now. So now, within our style sheet again, we will add a class of the page now, and we will attach some styles for that. This great eight background color. We're not gonna focus too much on the styling, but we just want to be able to modify a little bit to make it a little bit more presentable . So that's add a margin to the bottom. So the latest posts text is very large, so let's try to control the size of. But let's go back to our view on will change this to a paragraph tag. I will touch a class, and we can make this a different heading based on the class. So this is part off the bootstrap classes. It's already, let's looking much better. Andi again the same for the links, so they're really large right now, So let's go to our partial for the post. So again, let's make this a part a graft tag, and we can reduce the size of the text based on the heading size we use already. Listen, starting to look a little bit better so it's not a sidebar to our home page, so we'll break up the layout within our on page view. We'll break it into a two column layout. The wider column will be on the left and then on the right we will have a four coal mailed . So in the right column, B will create a title. McColl is about on the middle input some dummy text here. So now once we reload the page, we've got this content on the right off the homepage, and you can see that on the older pages, they do not have that side bar. So now let's add a food er area bottom. So we already have a partial for the food. Er So previously we had these scripts within this food, er we're gonna take those out on, but, um, directly into the application layout, lose will go at the very bottom. We will keep the footer specifically for food or texts such as the copyright symbol. So this create the text for the food er and we want to output a date here so we can use the date to be output dynamically. So we'll use the date helper, say date dot current so that we'll get today's date on EMI. Will format is using the string from time method. So so this method allows us to pass in a value will pass in the year symbol. We start with a percentage sign on de me. But in the why upper case, which gives us the current year. So now there's a line this footer with the content in the body tag. Well, Adam mark up for the container and will set a row and the colon on. We'll move that content inside. So now let's aligned much better. But we can also add a border to the top of this and space it out from the main content. So that's at an I D to this div. We'll call this food er, so let's on a border top, and that will be a solid gray border on, then will also add a margin 20 pixels, and we could add some padding to spaces out from the border that's starting to look pretty good. Now let's have a look around or application, so overall the page layout has improved, and you can take this further by styling this up completely differently to how I'm selling it right now. But the goal of this video is just to show you how easy it is to style your views. So we add classes on ideas into our views on then we other appropriate styling from the style sheet under the Assets folder. So overall pretty happy with this on, Let's move on to the next section. 33. Generate a New Rails Model: So let's look at how we can use the rails generate model to create a new model entry in our application. So it's open up our terminal on again. We're using the rails generate method this time are creating a model called category and we can pass in the values or our colons. Create a title, which is a string. I will also create a U R L, which is a Notre string. So once we hit the return button, rails will create several files for us. So let's get the list of files that are created and the two files that we are most interested in is the migration file Onda model to create a category model for us. So let's have a look at our migration file. So here we can see that there is a new table being created for categories and we have our two columns for the title and your l and we also have the time stamp fields for the created at on updated at time stamps. So now back in the terminal again, we will run rails, TV migrate. This will take this migration file. I'm running against our database. We can see that we've got a new table created. Let's look at the schema file and you will see the new table four categories. And finally, let's look at the new model that was created on. We can see that we have this new category model available to us. 34. ActiveRecord Validations: in this video, we will look at validating the data that gets saved in our database so we can do that directly from the model. So we want to control the information that gets put into our database to make sure later is in the right format to make sure there are no issues with it before we save it. And we can easily do that using active record validations, and that's we will be looking at here today. The first validation method will be looking at his validates presence off, and what this method does is just check to ensure lengthy column is actually set that there's a value for the title on the U. R L. In this case. So let's look at our post model. So by looking at our schema file, we can quickly figure out what columns we need to be validating for. So in this case, we have the title summary body on Active, which is a 1,000,000,000 value true or false value on the title summary are both strings text Andi, then the body is a longer text field. So not let's add these validations to our post model, so we know that We want each of these values to be set so we can use a validate to require the presence of these fields. So let's begin with the title field, and this time we're doing it slightly different were saying validates title and we will say presence true on this allows us to pass other options into this validation method. But for now this continue and add the color columns first. So that's add a validation for the summary and also for the body. So let's look at some other options that we can pass into this validation. So for the body, we could set a length and we can say minimum. We'll pass a number of characters into this validation. We could say 20 characters or 50 characters or whatever number we want here. Of course, this could also be a maximum value. So for the summary, feel that we can pass it in a maximum number of characters, since the summary should be a shorter value anyway. So now let's add our active column. So are active comb is a 1,000,000,000 value that would be a true or false value. Let's add some validation to ensure let a correct value set for like column. So this time we're using the n option I will pass in a true or false values are expecting to have a true or false value. The active column. So in our example, we can look at on this is just in the imaginary situation. But if you have something like a terms of service, it's kind of a tricky one to validate, since it has to be a checked field, so would be a check box on the front end on. In this case, we can use the option acceptance and set that true. So let's look at validating numbers now. If we had a field on this post model called Rating, for example, perhaps there was a rating for how could this post waas, based on the user's reactions to it, then we would want to validate that. That number is actually a number and not a string, so we can use the numeric ality option on passing a value of true and that just ensures that you have a float value or a number entered your value. If we were to change this field, name two views, for example, How many views on this post, then we would want to have a full number and not a float number. So you don't want any decimal points. So in that case, we can validate to say, Is this only in India? Jer? So we have the option to do that, using the numeric ality option again, but this time specifying that it is only an indenture setting. That too true. So let's look at one final type of validation here in this video. So we're gonna look at using the uniqueness. So here we could add a uniqueness true onto the title, and this would ensure that they're not two titles with the same name. So when someone tries to create a typical title, it would get an error message. And we can take this even further by passing in a scope option on. That means that we can attach a second column that we're checking against. So in this case, when we try to create a new post, if the title matches an existing post in the same category, then they will get a validation error. So now let's go back and clean up some of these validation rules as we're gonna keep it really simple for now and just validate the presence off these columns to remove all of the length requirements on just keep it as the presence. 35. Adding a New Model Method: So let's look at defining a new method in a model. So in order to do that, it's very similar to defining a action in the controller. So we used the D. F, followed by the name off that method that we're defining. So in this case, we will create a method called Details on this method will return a string. So we'll say this post was created on. And then we will return the date off the instance that is calling this method they created at when you use the string from Time Helper Onda, we will form at the date that gets returned. I will include a link to date formatting on this video so you can check that out. So this Try this out. Let's go back to the controller for posts. Andi, we can test it out on the show method to show you. Let's go to our view. You can see here that we are setting the post on the show view so the Post is already set interviews. Let's find the show in here. Then we can call the post. I'll put the value of the post details, so that is a new method that we created. So this should return a string. I want to reload the page. It looks like we have a typo, so you can see the toll. We have an undefined method. You can see here that there's a typo in what should be string from time. So let's go back to our model and fix the typo. You can see here we've got the sentence output It Onda we have the formatting is a little bit funny here. So can tweak this play around with the values off the time that's being returned. In this case, they're out putting the day, month and year. So this is a very simple example. But in the next video, we will take a closer look at model methods and how we can use them in our rails application. 36. Class Method vs Instance Methods: in this video, we will talk about the difference between instance methods on class methods. So by default, here are details. Method is actually a instance method, and the reason this is a instance method is because we're calling it while using a post instance. So we have an instance off this model already on. Then we call the method based on that instance, so that allows us to access values like that created at column class methods are run directly on the class itself. So let's look at how you define a classmethod and Ruby. So we do this by defining self dot and then followed by the name off that method. However, in this case, since we have a value here for the created at this will throw a error if we try to call it . So now that we have changed our method to a classmethod, we need to call it directly on the model. So now we can test this out. We should see an error. So we're getting a message here telling us it. The local variable or method created at is not available on. That's what we were expecting because we're not calling this on an instance off the post. So if he take that out, we'll see that the method does work. So this classmethod does work by calling it directly. So let's put this method back to how he had it before on. We'll look at adding a new classmethod just to see. What we can do is that as an example, let's create a new method. We will define this method as self taught total, so including the self taught at the front of the method name will make it a classmethod. I will add a comment just to make it clear what we're trying to return. So the most simple way we could make this is to return all off the results. So in this example, calling post dot total would be exactly the same as calling Post thought all as the post op total is using the all selector for active record. But it could return a size. Since all of the posts are being returned of an array, we can call a size method to count the items in the array. So this will make it slightly different from calling post thought. Oh, well, give us a count of all the results. So let's update our view to see how this looks. So we'll keep our instance method for the Post op details. I will also add a new paragraph and output the result off our classmethod. What's a post dot total and that should return a number and we can see that that is now working. And we get simplified even further by simply changing this to count. So that would be calling Post or count, which would give a number off the results. And I was still the same. Once we reload the page, there are many more things that you can do with the classmethod. But hopefully after this example, you can see the difference between the instance method on the classmethod. 37. Active Record Associations: in this video, we will be talking about active record associations. So in order to help explain that and going to begin by creating some new models within the Up Models folder, this will be used for demonstration purposes. So I'm creating a new model called Comment, and we don't have a database table to back this up yet. But we're just gonna be focusing on the models to get a better understanding of how the data is associated between different models. So will also create a new model called User. So what we want to do here is really think about the relationship between the data. So in our example here we have a user model. So each post is created by a user, so therefore a user will have many posts. So we describe that in rails using Lee has many command on. Then we passed the name off the table. So has many is the name off this active record association. So let's go now to the posts model. So we already know that a user has many posts. So there for this post belongs to a user. I'm probably the most important part of these associations his lead. It tells rails where to expect a foreign key to be placed in the database. So in this case, we have has many posts under the user model. So we're expecting that post each of those posts to have a user I d attached to it. Now, in this case, we don't have such a field on our table. But if we wear to have that field, it would look a little bit like this. So it will be a industry value on it will be user i d. Now he should never edit the schema file in this way, because every time you run a migration, your changes will be totally removed. So you don't want to edit the schema file. But I'm just using that as a way to demonstrate how that would look in the database. So let's go back to our comment model now. So when we think about a comment that comments going to be attached to a post so in this case, the comment belongs to a post, and you can see here that we're using the singular rather than the plural, so that comment will belong to a single post. So then we should also have that post with a house, many relationship. So that Post has many comments. The nice thing about having these associations between models is that it really makes it easy for us to output the data later in our views, even in our controllers are model methods. We can easily select the data that has that association. So this output this interview to show what that might look like. I'm writing this code. So in this case we have a post on, we can simply say Post doc comments, start each and live over the comments. And then within this loop, we can simply reference the comment directly, and we can call a column that is attached to that comment. One example would be the comment body out. Put the body text of that comment so it's very easy to base code around these associations , which makes it really nice toe have in your models. So I'm going to delete the code that we added that this was some example code to let you understand how these associations work. But you can delete these models for now, Andi. Then we will try to create a real world example in our application. So we already have a category model on The idea behind this category is that it will contain many different posts, so each post will be assigned to a category. So let's go ahead on create that relationship. So I have added a has many association and then within a post model, we will add A belongs to. So this belongs to would mean that we can call Post DOC category on. We will get the record for that category. However, in order for this to work, we do need to add a column to our database. So this means that our post model should have a category i d. So we look at the schemer right now. We don't have this column, so we'll have to make a migration to add in your column for that. So this is just to give an example of how it works in your building, an application so back into our command line. Now it will say rails generate migration. In this case, I'm going to use the shortened version off generate rails, G migration. We will call this migration at category I d two posts and then we will pass the Callegary as a reference. We'll call this references. It's a field type, so you can see that we have a foreign key created for us. We have a no value of false also, and this reference is getting added to the post table. So now let's go back to the command line and run our migration in the command line. We will run rails db migrate and you will notice that we get error when we do this on. The reason for that is that we're adding a category I d. On that category, I d must contain a value that is not all. So in this case, we already have entries in our posts table. And since this is a new column that we have added, there is currently no value set for this category I. D. So there are a couple of options for handling. This one would be to delete the injuries that we already have in our database. But a more simple solution is to remove this no house option in our migration on. We can add that later as a separate migration if we want to, but it will get us past this current problem. So let's run our migration once again. So rails TV migrate from the command line on this time it is working correctly. So going back to the browser now, everything is working again on gonna delete the to and raise are already created for our posts. Andi, let's see if we can get the new post to include the i. D off the category. In order to do that, we need to add a field to the form and we can see here that we've got our category I d set within the post table now. So let's go to the form Partial far posts. So in here we will have to add a new field for this form. So we'll change the label on the name of the field to category. We're going to use a select field to display the categories, and I will post a link to the details off using this form helper and the additional resources section. But here we're going to use category too old to select all off the values in our table. I'm gonna collect those values, and then we're gonna return to values in an array format. so that would be the I. D. On the name off that category. So the name will appear on the front end when the user is selecting from the list on the I . D will be saved as the option value off that select form. And since we're adding a new value, we will need to add it to our controller. So the bottom of the controller we are white listing these parameters that could be saved to our database on one final change I have just made here is adding the I D onto the view. So I have pre populated this category field, and I'll talk more about how to do that using the rails console. So I have a separate section on this course about how to add data to the database tables using the rails console so we can also add edit delete. Using the rails console will cover that more detail in the rails console section of the course, but for now we're going to complete the form on adding your post into this category. So just add some dummy content on hit the create post button. So now that the post has been created Let's go back to our views again, and this time I'm going to the public view by the home page. And then here I want to add some additional information about the categories that we have available at a new headline your title categories on. Then we will hit rate over the categories that we have in our database. So we're going to populate these as an instance variable from our controller. But before we do, that is just but the code in place to output the values for those calories. So here we will say category about putting the category DOT title, and then it will also output the value to represent how many posts are within that category . So we'll call a method called total category dot total, and I will return us a total number. So we'll have to create that method yet. So we're up this in a paragraph tag, and then we will go to our controller or public controller. And in here we will set this instance variable or categories was a category all so this was like all of the categories in a category table. So now let's go to our category model on. We will create this method up with the total number off posts. So this is a instance method within the model. So we're calling it against an instance off the category. So we'll say posts dot count. We're gathering the total posts within that selected category this moment in time and you can see it working here in the front. And now we've got one post within a ruby on rails category. 38. Active Record Callbacks: in this video, we will look at using callbacks within our rails models. So before we do that, this create a private section within our model. Andi Will is the method that we create as callbacks underneath this private section. So it's credit method called post log message, and the purpose of this method will simply be to post a message to the real server. So now let's look at the coal box and are available to us. So in order to create a callback, we used this format off before underscore validation or before underscore save before underscore, create on. We can also do a after underscore validation after create after save. So these make it really simple to trigger your own custom methods at certain intervals. So in our case is changes to after create. So after a post is created, it will trigger this method called post log message. And I'm going to add a comment here just for reference to remind ourselves that we can had different callbacks based on the validation when the record it saved or when it's created. So if he usually before or after, create Colback that will only get triggered once for that record under is also a upbeat call back We're gonna have before update or after update. So any time our post would be updated, then we can fire that Colback. And also, when it is destroyed, we're gonna have a before destroy or after destroy Colback. But for the purpose of this video, we're going to use the after create Colback. So that's output a string to the server log. I will say Post created with an i d off on. Then we will return the Heidi off this current record. So now this test is out, it will create a new log post. So it's input some dummy details here again. And what we're trying to do here is test this out for the after create Colback. Once we click the create post, we should see a message in our rail server. So let's have a look now in a real server to see if that happened and you can see the new record being created in our database. And then underneath we are seeing this string being output from our method. Now let's replace this method, try to do something more useful Land posting a message to a call this update Total posts count on. The purpose of this is to record the total post within a category. And we'll add that as a new field in the category model. So we can't have this method which grabs the count off the posts. But it's not very efficient once you iterating over multiple categories. So let's take our new method name on update the Colback so we can see here up The post belongs to category, so we should be able to call category. So this will be post out category is the equivalent of over calling here on we could dio update attributes update attributes was just update a single value inside this category. But there is another method that we can use and that method is called increment. In this case, we could call category dot increment and then increase the field total account. So this is a good fit for what we're trying to do here. The number as a second attributes we can set that toe one as we only want to increase our increments, this value by one. So now let's go back and look at our ski. My file. We have this tool account. Colon, If we look at our schema file, we do not have that colon in our category table yet. So in order to do that, we will need to create a migration and add that column. We will say rails generate migration. We will give this migration they name off. Add total count two categories on. We will set the column name of to account. And it is an indicator value. We can set a default value off zero for the insecure. So now in our command line, we will run rails to be migrate. So what this change takes effect on that has been added now to our schema file so you can check the schema file just to confirm. And we do see the total count calling Now. Now we can go ahead. Test is out. So that's stop the server and restarted again. Since we are modifying our database and I will go over to the browser and we will create a new post. But before we do that, you can delete existing posts. The reason I'm doing that as they do not have a count set for that category yet Phyllis out will choose a category it create on. Once we checked server logs, he can see that the entry is made in the database, but we don't see any update record for our category. Colback Let's have a look at what we did wrong here, so this looks correct. But we did forget to save the category. So if you typed out save at the end, this should be now working. So once we fill this out again and submitted, we can see this time that the category is being updated with the new total account for the posts. So that's working correctly. Andi, I think it gives you an idea off how to use cold backs within your models. So let's try this again with a different post. Oh, pick a different category and again, we've got a updated to account. I'm feeling us out a few times just to make sure it was working correctly. Will pick the ruby on rails again this time, which should put this up to two. So when we go back to the home page again, we still have the old approach to giving these totals for the categories. And if we look at the rails server. We can see the problem with our first approach, so it makes a query to the database every single time. It wants to count the post any category, so it's not very efficient. So let's look at how we can make this more efficient. So in our view, now we can see we have our title being output. We're calling this method category dot total, So if you go back to our model from the category, you'll see that it is carrying out this count every time it's removed this method onda, we will return the column from the database instead. So the total count is a colon in the database, and you can see that it works the same way, except when we check the server logs. There is no additional queries to the database to make this work. 39. Scopes and Scope Chaining: in this video, we will be talking about scopes, how to use them in your model scopes allow us to create custom queries that we can use to fill their data from our database table and we create them directly within the model. The syntax for doing so is pleasing the word scope, followed by the name that you're assigning to that scoop. And then we pass in a block of code as the second parameter. So in this example, I'm going to call a scope active and within the block off code is a second parameter. We will at a where clause we want to ensure that the active column is true. This will pull back. All the entries in our database table have a active value off. True. So now that we have our scope created, we can actually use it within the controller. So on the public controller, then we will change this post ought all to become post are active, so we can simply add on our scoops to the model. In this way, going back to our model again is create a second scope and we will use this scope to order the data that gets returned. We can call this order by latest. First on what we're trying to achieve here is to pull the results in a descending order based on the created update. So this time I would use the order statement. We will usually created outfield. So this time stem that's created automatically for us and that will be ordered in descending order. Now, one of my favorite things about Scopes is that we can change them together. And we can do this in our controller. So right now we have posted active, we can simply at on our new scope to the end becomes poster active thought order by latest first so by us changing these together rails, configure it out and create a statement to pull in data from the database. So let's go back to the browser and test this out and you will see now the order of the posts have been reversed. So now we will create one more scope on this scope will be used to limit the number of results that gets returned. So it's good to create scopes that do not do too much, all the ones. So that allows you the ability to pick and choose which ones you chained together on this example. We're calling it limit five. Andi, I think even we can change this to a lower number. Since we only have three posts, the moment changes to to just to see that working for us. So now let's go back to our controller and we will chain on our last scope. So if we go back to the browser now, we should be only getting two results and you can see that that is working. Now we have the two results ordered by the creative that in descending order. So if we look now at the rail server, we can see what's actually happening here. So Rails is building as query based on all off the scopes were passed in so we can see that it is only selecting active to be true. Andi. It is ordering in the descending order, and it's limiting the results to to items that could be returned 40. Rails Console and Sandbox Mode: the rails console allows us to interact with our database, and we can access it directly from our command line. In order to access it, we type in rails, Consul and hit the return key. Now we can select data based on the models that we have in our models folder. So we have a category model on a post model. So to see how this works weaken type post, don't all so the first letter off post should be upper case. So all model names must begin with a uppercase letter and you can see the results returned in the console in order to exit rails console. We can type the word exit head through a turnkey, and it's worth noting here that any changes you make in the rails console will be reflected in your database. So if you delete a record, it will actually be deleted from your database. But in order to get around this, we can run the rails. Consul in sandbox mood. We do that by passing the hyphen, hyphen sandbox. We pass a option sandbox on. This means that once we run and it commands within the rails console once we accept Consul they will all be reverted, rolled back. So as an example, I'm deleting or destroying the last category in our categories table so you can see that it has been deleted here and now. Once we exit, we can see that were ruled back. So this rule back means that the changes would be reflected once we access the console again. So this time I'm going to sign in once again on we'll check the last category and you can see that there is still here. It is not being deleted, so that's pretty useful. If you want to explore your database, entries play around with things and not have to worry about causing problems with their database. 41. Active Record Queries: In this video, you'll be looking at active record queries on how to use them within rails Console Let's start up Our veils console will use the shorthand version Rail Sea to start the console and the sport, noting that the queries that will cover today can be used within the model controller and also in the rails console were just using the console as a means to cover these and discuss them in more detail. So the most simple of these queries Isley dot all so you can use any model name Adlai Don't old query to select all of the entries in that table, and we can also see here that they are surrounded by square brackets. So this is an array that has been returned once we call the old Method. Since it's an array, we can use dot size to count the items in the array. So next we look at using the dot first query, so this allows us to take the first entry in a table, and that is started by I D. So we get the very first entry using the model name dot first, and we also can access the last item in the table in this case will use category don't last and again the table is started by I. D. If you want to quickly see what columns are available for a specific table, you can type the model name plus dot knew at the end, and it will output all of the column names on the current values that are set for those column names. So in this case, they're all nil if we create a new object, if you want to access a specific value from an entry in the database and use the name of that column on attached lad to the object directly. So in this case, we're saying category, don't last title on again with had agreed Don't Last Stop created that we can also select a item from the table based on the i d. And to do that we used dot find on, we pass in a value of the I. D. So this is quite popular in the rails. Controller. You will see this based on the I D taken from the U R L. If you want to load an injury based on a different column name, you can usually find by method. This allows us to pass find by, followed by the name off the column that we want to find in this case, we will use title. We'll pass in a title that were searching for and then we can see. The result has Bean found and returned to us. So this time we will query using the don't wear on. This allows us to pass in different columns that we want to check against. So this time we will use the title column on again. We will pass in a value that were searching for, and you will notice that the result is an array on This allows us to pull multiple results based on what we're searching for. So previously, when used the find method, it will only return one result. So this change it up a little bit. This time we will search for an i D based on a value from Honore so we can pass it array directly into this on if the criteria matches and it will return all of the results. But you will notice here that the results were not ordered by I d. So that's at an order. Clothes onto the end of this query so ordered by i d. And that will be ascending order. So this means that we will sort of results based on i d on the lowest i d being the first result to be returned Active record also allows us to create custom queries based on sequel . So in this case, we can right our own conditions on will pass in a parameter into this string Cole name of title animal past the value of title in the second parameter. So the question mark is used to determine the placement off that variable like it's passed in. And we can have multiple values added in this way, and you can see that it creates this query for us based on the parameters that we pass in Rails will build query for us. So let's have a look at how this might work if he wanted to filter by date. So in this case, we have a created that time stump, and we will compare that based on a date time value that we pass in other parameter. So on rails it's very easy to manipulate time, and this way we can say one dot a ago are one dot day from now on the week ago. So this is built into rails and it's very easy for us to take the current time stamp on roll back one day or one week. So in this case we are filtering by Andries are created more than one day ago, and you can see here that the time stump is included as part off the query we looked at using the model Don't wear to build queries on this time. We'll look at passing in more than one value, so this make a condition that is a little bit more complicated. Floor our Cleary. This time we will select values that have an I. D between one and three and has a title off Ruby on rails. There's very specific criteria that we're setting here, and we can see that the query is built from all the variables that we passed in. If you want to build a query based on values that are not present, then you can set the where dot not so we simply change the Giller where under not on. Then it will find results that don't have that condition, don't meet that condition. In this case, we want to find categories where the title is not Java and we could see all of the other results have been returned. So using active record, it's quite easy to build queries in rails. And in the next video, we will be looking at how to create new entries in our data Bees from the rails console. 42. Creating New Entries from Rails Console: in this video, we will look at how to create new entries to our database tables directly from the rails console. So this begin by tapping our model name dot new. So in this case, we're doing category, don't you? Which allows us to see all of the column names in our table. So now I'm going to assign this to a variable. So I created variable called cat C 80 on this allows us to pass the values for each column individually. So in this case, we will create a new entry for PHP. Well, said the title Ph. B also said the Earl to PHP. And now if we type out are variable and hit return, we could see the values I've been set already. So in this case, we've got the title value on the your l on. These other columns will be updated automatically once we save this entry. So now we can call cat dot save and that will create the new entry for us if it is valid. So we can also check. It's valid by typing dot Valid question mark. So this just means that our validation rules have being passed. So now we will hit Captain Seve. Andi, I will give us our new entry into the database. So just to confirm that it has been saved, you can type category don't last and we can see our new entry so we can see that the idea on the time stamps have been created automatically for us Another way that we can create entries in the database from rails console is to use category dark create or your model name dot create, and then you can pass in the values off the columns that you want to create. In this case, we will set a title on the U. R L So not once we hit the return key can see that we have a new entry created. So let's look at the muzzle. Don't new method again. So this time we will pass in a value when setting the new entry. So we will set the title. We're assigning this to a variable and you can see that one field has been populated. So now this check to see if this is valid and it's not valid since we do not have a URL, we have a validation rules for the girl. So if we try to save now, you will see that it does not work on. If we add the exclamation mark, it will give us the validation reason are not saving. You can see your own can be blank. So now we can populate TRL. And now, once we try to save it should work this time. 43. Edit and Destroy Database Entries from Rails Console: So far, we have looked at how to select data how to create new data on this video. We're going to be looking at how to update and also how to destroy records in our database . So let's begin by updating a entry. So let's get the category. Don't last. And here we will update a single column so we'll use the update attribute Method on will pass in the name of the column that we want to update, followed by the value that we're setting for that column in the second parameter. So now we can see that it generates this update statement on. We are setting a new value for that entry. So now let's look at how you can update multiple columns at once. And you can do this using the don't update method that we pass in the colon names that we want along with the values so we'll set. The title will also set the u R l. And you can see that multiple columns have been updated for this entry. When we want to update more than one entry in our table, we can do that using the update all method, so update underscore all, and we can even built a query in front of that so we could Filter is based on the title that created at date. So for the update, all the past in the field that we want to update, we could add multiple column names here, so we'll set the tool account. Zero. You can see that seven entries have been updated in this example. So now let's create a variable on a sign the first category to that variable. So this time we're going to update it field for an existing record. So that's update the u. R L. Change this to rails, and then we will save this record and you can see that the euro has been saved. So we've looked at how to update records. But now there's look at destroying records. So when it comes to destroying entries in the database, it can also use the destroy, underscore all method. That's a lot like the update, all method. We just looked at Andi. You can filter the results before you call a method, and it will delete all the items in the tray that's returned. So this time this look at selecting a single record, and we can call the DOT destroy on a single record, and I will output the values off that record before it deletes it. So that's really useful. Outputs the details first, because it means that if you make a mistake, you can take that data and create a new entry based on it. So we could simply copy these column names and values create a entry over again if we needed to. So let's write a query that select some data and then we will delete the data that gets returned. So this time we're going to use the where and will say, creator, that is more land $12 hours ago. So we're combining some off what we've learned in this last couple of lectures on, we will apply it in this final example. So we're selecting the data that we have created very recently, and since this will return on a rate, if we call the DOT destroy, we will get an error. So see how it looks So you can see here they're telling us there's a wrong number of arguments, So what we can do for this is the destroy underscore all that will delete. All of the items are returned on. In this case, you can see that there is multiple destroy statements created. Andi. It has deleted two entries from the database. So hopefully by now you're comfortable using active record on the rails. Console on all of the active record methods that we've covered in this past few videos can be used within the model on the comptroller of your application. 44. Asset Pipline, Webpacker and Yarn: in this video, we will be looking at the asset pipeline and rails so you can think of the asset Pipeline has a framework that rails uses two men if I compress and compile our CSS and our JavaScript. So this means that we could write our CSS using sass on foreign JavaScript. We could use typescript or coffee script or some other framework for the front end, even though we're using on alternative to JavaScript or CSS. Rails would still know how to compile it down to those CSS and JavaScript files so that we can use those in production. So let's begin by looking at where to place your style sheets. So any CSS you have any sass files you have now these go under the APP Assets Directory on Under the Style Sheets folder. Now, by default, Rails will compile SAS into CSS for us, so that happens without us having to change any settings within our application. So if we wanted to create a new style sheet, we accept it. Created as a new file inside the APP Assets style sheets directory, Andi. Then we were placed any images that we have under the assets images folder. However, in Rail six, the JavaScript directory has moved, so it used to be under the Assets directory to now it has its own folder under the APP directory. On this application dot Js file will act like a manifest file so it is used to pull in, aren't could on compile it into a single file. So the best way for us to work with this is to set up our own folder within the JavaScript directory on use like a require statement. Pull in that coat. So this case I'm going to create a includes directory on ad the Post's dot Js inside of it . So any code that we would add to this post dot Js file would be compiled inside this application. Js file. We also have a vendor directory. We can see here at the bottom. We have this vendor directory. Previously, an older versions of rails all of our javascript from third party libraries would go inside that vendor directory. However, in Rail six, we use Web packer on yarn. So Webb Pachter is used to compile the files. On yarn is a package manager that downloads the files so yarn can be used to install third party libraries, and we do that using the terminal. We would type yarn, add followed by the package name. And once that packages installed, then we would add a require statement here to pull that code into this file for compiling. If you prepared working with the Assets directory for your JavaScript, then we can quite easily roll back to how things were done before. So in order to do that, you would create a new folder called JavaScript under the Assets Directory, and in here we would include a manifest file. So I just created this one as an example pulls in the libraries we need on them within the application layout under the Views Layouts folder, we would simply change this JavaScript pack tag to be JavaScript include Tag and that will take it directly from our assets directory on a low. We won't be diving too deep into Web Packer on yarn. In this tutorial, I wanted to include a brief description of how you could rule by to make use off the asset pipeline for your javascript. However, I do think it's a good idea to adult the use of wet Packard and yarn in our application. So I'm going to remove these files that I used as an example so going back again to our vendor directory. So if you want to include third party scripts, third party style sheets that can be done within the vendor directory. But in order to set that out, we need to create a assets directory. So this needs to be the same structure that is in our assets directory. So in here we can add a style sheets folder, and it could. Also Audi JavaScript folder have wanted to include any JavaScript libraries using this approach. 45. Images and Asset Urls: So within our assets Images directory, I've added to stock images that we will be using on adding to our application. So let's begin by adding an image to our view when adding an image that is saved in the images directory under assets. We need to do this using a helper, and there's a helper called image tag, which allows us to generate an image. So the first parameter that we pass into this is the path to our image. So that path begins from the images directory. So in this case, we just need to file name. We can also pass in additional options for an old tag. We're gonna have a with, and we can also pass in some class names for our CSS. In this case, I'm going to use a image fluid class. So the image fluid class is part of bootstrap, which we have included on our application already. So this test this out on how we can see that we have an image on our home page. So it's actually quite easy to add an image to the view, and you can add new classes. Toe this to space it out style it up a little bit more if you wish, so I'm adding some margin to the top and bottom. We can also pass in some CSS styles, so in this case I'm going to use border radius on. We will apply a six pixel order radius to each corner of image will also add a border, say one pixel solid border around the image. So using the image tag helper, it's quite easy to include an image on. Also style it up in whatever way you want, we can add additional styles, had classes to it. So now let's look at adding a image to our style sheet using the SAS file. So in the SAS file, we can use a image or l helper again, and this time it will pull the image directly from the Assets Images folder like before. So this will be commonly used to create a background image or a image sprite in your style sheet. So that is working now from our style sheet. So let's look at using a asset. You are l helper, so this will be useful if you want to do something with the image path. Our image you are l within the views. So this add this to our application layout will input a style tag onto the body. Andi, just to test this out, we're going to set a background image. So using the asset you are l, we can output the exact address of where the image is located. So once we see that working in the browser, it will look exactly the same as it did from the style sheet. But to make this more clear about why we use these helpers, let's have a look at what the you are. L is being output as so that paste is directly into our view to see what the result is. And now you can see why we're using this helper. So when rails handles images from the Assets directory, there is a digest or a string of characters, including letters, numbers that is used to cash that image. And since this string off text will change every time our assets are modified are compiled , we need to use the helper to figure out what the exact path of the images to make sense, to use a helper to handle anything image related and rails. So now I'm going to go back and tidy up our styles a little bit. So include a white background on the center of the page and will also do that on the future of the page on. Then, within our style sheet, we will activate this background image. Now we have the finished product. So this video we've covered image tags covered background images in the style sheet have also covered using the asset your L to output image addresses. So in the next video, we will be creating our own custom helper and using that to simplify our views. 46. Custom Helpers and Views: in this video, we'll be looking at using helpers how it can improve our views. Now the main reason to use helpers is to simplify leb logic and de clutter our views. So the first thing we can move into a helper is the page title. So right now we've got this content for line at the top off each of our views. So let's reduce list, simplify it down and we'll call this helper Method page title. So now let's go to our helpers directory. So under app helpers on, we'll look at the application helper first. Now, this seems like the most logical place toe have this helper method since it is used throughout the application. So the structure for setting up a helper is to create a new file under the helpers directory. And then we'll give this helper a name. In this case, we're going to create a categories helper. What type? The word categories, followed by an underscore the word helper. And then you add a dot RB extension and then within the file, we open up. A module on this module would be called categories helper, and you can notice that the name of the module is using Camel case, so the first letter of every word will be uppercase within this module. Then we define a method. So the approach to defining a method is the same as it isn't a controller under in the model. So let's go back to our application helper on. We will define a method called Page title. On this page, title will accept one parameter that gets passed into it. So I think we should change the parameter name. That's it's exactly the same as Help her name right now changes to title so the title gets passed in, well, paste in the code that we have before. So it creates this content for that passes it into the page title so that we can yield it in our layout's file. But the value, like gets passed in is a parameter that we're using, and in this case we can ensure that this is converted to a string just in case the user passes in Honore or some other different type of data. So it's forces to a string. So now let's do the same for each of the other pages. We'll just use the helper to set the page title so it leaves the views a lot cleaner on were less likely to make mistakes in this way. So now once we creek through each page, we can see the title of the page changing networks using our new helper. So the next thing we can look at doing with a helper is to create some information about each of these blowing entries. So perhaps saying when it was posted on which category it was posted in. So there's open up our partial for posts slash coast in here we will, but a new line underneath the title of the post and we'll output using the equal sign. In this case, we want to print out the value off the helper method that we will call. So this help our method would be called post underscore meta On this will be the summary off the when the Post has created at which category it was created under. It will pass in the post to this helper. So now in our posts helper file, we will add a new method. So this will accept post, so we will return The post are created at a time stamp we can pass this into a helper called time ago in words. This helper allows us to take the time stamp and put it into words, and we can add some text. So this to say that this was created at and since the time ago onwards will to return a string so we can add these two strings together using the class symbol. And then, after the time ago inwards, we will add a new string to say Go. So it's created one day ago or 10 minutes ago. So now we can see that this part is working already. So now let's add the category name to the end. So it's add on post category, don't title, and this will return the title as a string so we could see that this is working now. Each of the posts are in a different category, and hopefully this video has shown you how easy it is to add helpers and rails. 47. Creating Custom Forms: in this video will be creating a custom form using the form helper on just to cover what we want to do with this form once we go to our blog's show page. So on this page, once we visit this page, we want to have a form so we won't be seeing this form on the front end of the site. This form will also submit on it will store a view count in the table for the posts. We'll have a Views column in the post table. Andi that will track how many visitors have you disposed? So it's begin Mike reading migration. So in this migration, we want to add a new column for views, and that will be an integer value. I had a default value off zero. So now this run our migration And if we open up our schema file, we can see that the new colon has been added to our post table. So now let's go to our post show view On in here we will add the post meta helper that created earlier, So this will output the creative that on the can agree that the post is currently in so I'm going to add some basic formatting to make this a little bit better on the front end. We'll bring the text down to a smaller size. So now we will render a partial at the bottom of this file on this partial would contain our new form. We'll put this partial inside the posts folder. We will call it view form on. We will pass in a local variable cold post. So now we will create the new partial file. We're going to use a form with helper and this will allow us to create the form. So the normal way to use this. So the normal way to useless form helper is to pass in the model Andi. Then it will, by default, create a farm to post our data to. And there are other options that we can set within this Helpers, such as a remote form so removed form is sent by JavaScript. The form submission is made by javascript. Andi. That means that we don't have to reload the page so we can use this form dot hidden field to output a hidden value in our form and we'll give it a name off. I D and we will set the value off this hidden field to be the post, though I d So now let's have a look at the source of our page and you will see the form has been created. Andi, it has a hidden field attached. We have multiple hidden fields. One is for authenticity Token, But our post I d is here at the bottom and you'll see the action is posts slash nine. So this farm has been created to update existing post. So we're going to remove this remote. True as remote, True is set by default. Once we used a form with helper and we actually want to change this model post option so we can use a you earl option here on. We could pass in a specific girl directly, but a better way to do this is to pass in a path that we create from the Routes file. Let's give this a name. We'll call this post view path. Now we have to create this in our routes file. We'll go to our CONFIG folder and open the routes file. This time, we will create a route that is using the post method on the route. Entries above. We have used a get request. So this time we're setting as a post request. So the u R L is visible in the browser will be post slash view. But of course this is happening in the background, so we may see that address on our server, but we won't see it on the front end on. Then we will point this to the posts controller on that will have a method called save post view. Let's create that action now in our controller. So let's define our new action. We can leave a comment here to say what we're planning to do with this action. So you want to increment thieve, you comb the view count for the post. So now let's see what this looks like on the source code of our page. So now we can see that the action has changed pointing to post view, and we've got the data remote true by default and our method is post, so this should work. So if you want to change this method equals post, we can pass an option for let into our form, and now you can see that the forum has been updated and in fact, we've lost the authenticity values when you do that. So put that back again and you will see that authenticity token input into our form. Another thing to note here is the name of our input field. So right now it's just called I D. But if we wanted to put that in, say they post we could pass in a scope so I would wrap it in a post prom. So you can see now, once we reload the page, any values inside a form would be wrapped in the post Graham. So now let's go back to the Post Controller. So here I will add our new action to this before action builder. Well, it means that we will have the post instance variable already preset for us. So what we gonna do here is post dot increment on will increment the views column and we'll increment up by one. What we could do here is you could actually add this into a conditional statement to say that if this saves, then execute some more code and in otherwise return a different response. But for the purpose of what we're trying to do. I think we can just call it once and not wait for a response. So this form will run by Ajax in the background. Andi, we'll just trust that this saves in the background. We won't be listening for a response from this method. 48. Custom JS and Remote Forms: those begin by adding a HTML option to our form helper. So this allows us to pass in i DS classes on all arranged female attributes that you would normally find in this case, we're going to add an I d. And we'll call it say views. And the reason we're adding this idee is so that we can access it from our JavaScript file . We're going to use the posts Js within our JavaScript includes directory. What this will do is we're going to be grabbing this form on submitting the form on by default. This form helper generates a remote form. That means that the data will be sent by Ajax in the background. So simply selecting the form on submitting it should be enough to do what we need to do. We're going to use plain javascript to do this. We'll begin by adding an event listener and we're gonna be adding that event listener onto terrible wings. The Winter Ball links has finished loading the current page. At that point, we will check to see if I form exists using the I. D. We can do that using the document dot Get helmet by. I d and this will select the form for us. Now we have to bear in mind that this form will not be available on all pages. So, for example, once we're on the home page, we will not be using this form. This check to see if this form is now Andi Onley. If it's not know, then we will try to submit the form. So just to recap what this code does once the event is triggered for the turbo links load and we are running this function on this function will select the form using the get element by I d. And then it will detect if the form is present. Andi, Then I will submit the form which will make the request to our controller. So is give us a try to see what happens. Reload the page. I'm gonna click on one of the posts. So now this should have run in the background. But it's open up our rail server and you can see here that the post has been updated to the views have been updated. So that has worked and you can see the massive name for the action name in the rails server we can reload the page again, and now we can see that the views has gone up to two. We're incremental that every time the pages loaded Now what to check the second post and it is gone toe one. So the views has been set for this post. So now let's see how we can output this fuse into our post meta helper. We're hoping up to help her file and we've already got our time when the Post was created and what category. So it's add on the view account. We're adding a new string, and here we will say, post viewed Post has been viewed and I'm going to use string interpolation to in purty value off the views. So update doesn't hire helper to output on single string. So right now we are adding multiple strings together, which is a bit messy, so it's clean this up a little bit. So now we've converted this to one single string and we are using string interpolation to insert the values. So now every time we reload the page, we should see the view count updating 49. Data Formats and Strong Params: in this video, we'll be looking at two different things. The first thing we'll look at is the strong parameters and how they're used. And controllers. Andi, you may notice this post Haram's method at the bottom of our controller on the reason we have this is to restrict Lee column values that we can submit from our views. So this is a security precaution. So in this case, we are white, listing the fields that we are allowing to be passed from the views and to the controller. If the cold name is not present in this permit option, then it will not be allowed to be used within the controller. So the main use case for this is when we are creating a post or updating your post. So we restrict the values that could be passed in to our controller. And if we didn't use, this would be very easy for users to modify forms on the front end of the website so they can simply manipulate the data on control. The columns that get passed in to the controller so they could end up updating information , but they're not supposed to on. That's the reason why this post Grams is here, so this gets generated automatically when I use a scaffold to create the controller. So it's worth noting that if we add columns to our database using a database migration, we will need to update this Paramus at the bottom of our controller in order for that new column to work within our forms. So now we'll have a look at the show view on the next part of what we want to cover in This video is handling different data formats from the browser, so in this case, the default format is HTML. But we could use different formats here, such as Jason JavaScript or even a plain text format. So this begin by adding a respond to block to respond to allows us to detect the type off request So the respond to Helper takes a parameter on will call a parameter format fill that allows us to obtain information about the current request on. In this case, If it is HTML, the default functionality will be card I for HTML, so it will render a show view if the format is HTML. But if the format is Jason, then we will pass a block of code toe handle that Jason format. In this case, we're going to use a render on. We haven't looked at this yet, but you can render as Jason on. Then we will call post on to Jason. So it allows us to convert the post object to a Jason output. So normally, when we call a render, we're rendering of you. But in this case, we are not loading. A few were simply out putting the response as Jason and we can see here the top everything . That before action to set the post a post gets sat down here at the bottom in this set post method. So we're simply grabbing that post on converting it to Jason. So let's have a look at this in action so we can modify the u R L to have a dot Jason at the end, and now we can see the Jason response for our post. So now let's look at a different format. In this case, we will do a text format, and for that we can render a plane response. But we could also render a hte email response here, and this time we will return a single value from this post, so it will use the title. Now, when we use the dot text extension, we can see the response from that title. One other thing to note here is Lee render Jason and this example We don't actually need to call it to Jason. So rail the smart enough to know that we are intending to output is as Jason so handles this for us. We could include other formats here too, such as XML or pdf. But for some of these four months, we would need to add additional code to get them working correctly. 50. Form Validation in Views: in this video, we will be cleaning up our form on the main thing I want to change here is take out this for invalidation messages on moving into its own partial. So right now, the rails generator will create this validation code on is quite a lot of code to be having in every single form, so it's much better if we can share a partial on render that partial within each form. So we'll keep our views a lot cleaner and easier to maintain. So begin by referencing that partial so we will. But that partial within the Layouts folder. We will call it for invalidation and will pass in a value so we'll be passing in the reference to the model. So we will name that variable item. So let's create a new a partial file. We're creating that inside the Views Layouts folder this week called Form Validation. Well paced this code into it. So now this modify it to use the item we named the local variable item. So let's update all references to use this new variable, and I think we can actually remove this. It's to tag entirely. I don't think we need that we just really need to have the list off error messages. But we can also do. Here is check to see if Lee Local Variable is assigned. If it is assigned, then we will check to see if has any error attached to it. And if it has errors, then we will live over those error messages. So now let's try to create a new post. And what we want to do here is really see the error messages like outward. So it looks like we made a mistake in our template. Let's have a quick look and see if we can fix that to go back to our form, and we forgot to close off this partial. So now, once we had to submit button, we get a list off message is coming back from our validation rules so we can use this partial across any forms within our application, simply by passing in the model instance 51. Creating a New Database Migration: creating a database migration and rails is very simple. We can do that using the generator and the command line, so we'll type rails, generate migration and we can actually shorten the generate to use the G so we can say rails G migration and then we will give this migration a name. The name is important if you are creating a table specifically. So to do that, you will say create underscore, followed by the table name. And then we can pass in some column names, those credit first name as a string and a last name and also an email. So all three are strings and finally will have a password, which will be a hashed colon so we can use the type digest for that. So once you run the command, it creates a new file for us under the DB Migrate folder. And in this migration file, we already have the code in place to create our table. All the column names have been added for us. So in order to run this migration, we type rails db migrate once it has completed and we can see the end result within the schema file. Now we have a user's table at the bottom of our schema file 52. Add and Remove Database Columns: So now that we created our first migration, let's look at how we can add or remove columns in our table. Credit new migration to remove our 1st 2 columns, the first name and last name. And then we will also add a new column called User Name. So let's generate another migration, and we will give that migration suitable name. So in this case, we want to replace the fields in our users table. Now that's add the coat to remove our 1st 2 columns so we can remove a column by using Lee Remove underscore Colon and then we pass in the table name, followed by the column name. We're going to do that for both first name on the last name, and then we will add a new column. And then we will add a new column using the ad Underscore column, and we will input the table on the name off the column that we're adding. So when we're adding a new column, we want to add the data type of that column. So in this case it will be string, and you can also add our options to this column so we can say that We want this field to always require a value so we can set annulled falls. So back in the command line again, we will run rails, TV migrate to make these changes come into effect, and you can see that the columns have been removed and a new column has been added. So again we will look at the schema file on. We can see now that the 1st 2 combs have been removed and we have a user name added at the bottom off the file on the no set to falls. 53. Renaming Database Tables and Columns: Sometimes you may feel a need to rename a table after you have created it on. We will look at doing that in this video. So let's change our users table to a new name, so we'll create a new migration. Well, say, rename users to happens. So this has generated a blank migration file. So within the change method, this time we will add the rename underscored table. We'll put the first table name that we have followed by the new table name Andi. Then in the command line, we will run rails, TV migrate. So now, once we look at our schema, see, the table has moved completely. It's now at the top of the file. We have our table now named as at Mons. So now let's look at renaming a table column. Who can do that? Using a migration? Also credit migration. This time we will call it rename user name to name. So now back in our migration file, we will say rename underscore column. We will pass in the table name. So this time our table name is admits on. We want to rename the user name Colon. We want to change it to name. So now let's run rails tp migrate command line. And now, once we go back to the schema file, we can see that the user name column has Bean renamed. 54. Rolling Back a Rails Migration: So now let's look at ruling back a migration. So sometimes you may need to undo the last changes you made in our last migration. We renamed the user name column to name I want to rule out back. So this run rails db colon roll back. So that will under the last migration that we made, and at the top, you can see the name of the migration, plus the word reverting. So now in our schema file, we can see the old user name column again. So if I can are command line again, we can run rail Stevie Migrate to run that migration again. So even though we roll back and migration, the migration file is still in the Migrations folder, so running the migrate again will allow the change to happen again. So in this case, our column gets renamed to name again, and another option is to pass in. Step on. This tells the rollback how many steps you want to roll back or how many migrations we want to roll back. So in this case, we can go back multiple migrations at once.