Loading
Lesson 68
Courses / Software School
Build a Web Application with Ruby on Rails Framework - Software School (2024-07-27)

This lecture is a brief introduction to the Ruby on Rails framework to build a web server.

The Ruby programming language is used to write the code for a Rails application.

You can install Ruby from https://www.ruby-lang.org. You can type ruby -v in the terminal to see if it is installed.

Third-party packages in Ruby are called gems. And you can install them by calling the gem command. The lecture shows you how to install rails using RubyGems.

With the Rails command, you can then generate a new project. All the file structure will be generated for you.

Ruby on Rails follows convention over configuration (COC), meaning you have to following the set of rules laid out by the framework and everything will just work seamlessly out of the box.

The lecture shows you how to power up a Rails server. If you are on Windows (not WSL), you have to prefix the bin/rails command with ruby.

Ruby on Rails follows the Model-View-Controller (MVC) paradigm.

You learn to use the Rails command to create a controller and a view.

Then you learn about models.

Along the way you are introduced to SQLite that is used as the default database for the Rails app. You can always change that to another kind of database, though.

You learn how to access the Rails DB console. And you learn about the graphical user interface for SQLite called DB Browser for SQLite.

You also learn how to access the Rails console to run Ruby code and leverage the object-relational mapper (ORM) ActiveRecord.

You learn to show a list of products in the index page by using Embedded Ruby.

You learn to make a new page and defining the route, controller action, and the view.

You learn how to build a form using form helpers. Although you can always write HTML manually, Rails provides some helper functions that generate HTML code conveniently by just calling them.

You learn to define an HTTP POST endpoint that is used to create a product. You learn to define the controller action, taking the information submitted by the user via params, permitting the params, and finally using ActiveRecord to ultimately create the record in the database.

Video Transcript

Hello, today we will talk about Ruby on Rails, a framework to build a web server. And before we do anything, you need to have the language Ruby installed. Here's the website, you can click download Ruby, and there's many different ways depending on your system. The way I did it today, I'm using Windows, so all I did was use this Ruby installer thing, and it installs in C, Ruby on Windows, and if I look at the version here, this is my version, bin, the command for Ruby should be here somewhere, this one. And if it's already included in your path, if you're using Windows, you should call Ruby space-v, and it should recognize it. Let me show you my PowerShell. You can see here, Ruby space-v tells me I have it installed in the version. If you don't see this, it means it's not installed. Or probably it's not in your path, so you've got to make sure if it's already installed or it's just not in your path, so you've got to add it in your environment variables, the path, b-a-t-h. Okay, so with that, let's go, let me cd to a directory that I created, okay, so I created a directory called introduction to Ruby on Rails separated by a dash or lowercase. This is where I'm going to be creating my project. So you should find somewhere where you want to create the project. This is the way I like organizing, anyway. I got Ruby, and Ruby is the programming language that we're going to use. And it has a package manager called, it's called a jam stuff. So when you, if you're coming from JavaScript world, we have npm, right, and we install npm install whatever package. In Ruby, it's called a jam install. So basically you jam install Rails like that. They call the packages gems because, okay, Ruby. So you're going to run jam install Rails separated by a space. And that should install the Rails package. I'm using, in this case, 7.1.3.4, that's the version. Everybody got here so far, you have to let me know, otherwise we cannot, you're going to have trouble going forward. Okay, so now we have to generate a project that will pretty much create all the files necessary for a Rails application. So we don't have to write everything from scratch, okay? Now we're going to do Rails. That should now be your path of the gem install Rails and new. And then you give it the name of your project. I'm going to call intro dash to dash ROR, which stands for Ruby on Rails. And this should create the directory intro to ROR with all these files and directories. While it's doing that, I'm going to go back to the browser, talk a little bit about Ruby on Rails. So basically Ruby on Rails was created by this guy called DHH. That's his abbreviated username on the internet from Denmark. And he envisioned like a framework where everything just worked out of the bat without much, you have, you having to manually set everything up. So basically he wanted to have, okay, I just run this command and everything is already generated for me. All the boilerplate is already generated. I don't have to be working with that. And there's a lot of stuff in Rails that just works out of the box. And it's just a lot going on behind the scenes. It's called a Rails magic. You ever heard of that going forward? Some people like it, other people hate it. So it's a double edged sword. So basically Ruby on Rails got really popular, you know, back maybe end of 2000s, I think around that time. And because of its innovative approach of having convention of configuration, COC, which basically means, okay, we're going to establish a set of rules of how you're going to structure your web app. And you have to follow those rules and everything would just work out of the box for you. That's the Rails magic, okay? And that allowed for many people at the time, we had a lot of growth in the sense of many new companies being created. People had so many ideas, but they needed to do it, iterate over those ideas and come up with the apps very fast. So that's called a rapid prototyping. And Rails was just perfect for that because they could just, Rails knew whatever and they just create the whole app already working. They didn't have to set up all the database stuff manually. They didn't have to figure out, okay, how are we going to interface with the database? We need an object relational mapper and ORM. How are we going to do about the templating when we send HTML to the user? How is that all that stuff going to work? So it's already built in by Rails. So that's why it got really popular, so much popular that all the approaches that Rails kind of pioneered. We now use in many other different frameworks. And over time, Rails kind of be pushed to the side and become less popular because other frameworks adopted its own features, so you don't have to use Rails per se these days. But it's still used by many famous companies. For example, GitHub was built on Ruby on Rails. In any case, that's my talk on Ruby. I'm just going to jump into the code for the person just got here. Again, you have to download Ruby. Here's the link. If you don't already have it, the Ruby language. And then we go to the terminal and we run the command to install Rails. So you can verify ruby-v to see if it's installed, gem install Rails. And then we did Rails new intro to ROR. I paced the commands to the Zoom chat. You see it creates a lot of files here and all that stuff. So I'm going to cd to that, make sure I'm in that directory. And then you can open your text editor. For example, I can do code dot for Visual Studio Code on the current directory. And this is what it looks like. Let me show you my VS code. Like that. Let me open here in a different window to make it more focused, code dot. One moment. Let me know if you cannot get the project to be created, okay? You have to let me know. Otherwise, oh, just keep going. Okay. Let me do this other one. There you go. Okay. So these are the files that are created. There's a read me if you want to read, blah, blah, blah. But basically, if you come from the world, I don't know where people come from post where you're, what language you know, so I can try to kind of make some knowledges. But basically, a gem file is where all the dependencies are. This is called the manifest file. It's like package.json if you come from JavaScript. Basically you just call gem and whatever the package name. So this one, this project depends on Rails. And this is the versions. And there's a lot of other stuff that Rails auto-generates for us, okay? So I'm going to open a terminal here. It's a PowerShell, by the way, you can choose your own. And to run Rails, the server, you've got to go to this bin directory and call this Rails command here with the server option. You can do bin slash Rails space server. Now this is only for Mac or Linux. If you're on Windows, you've got to do an extra step. You've got to do Ruby before that. And probably you have to change the slash with a backward slash like that. So if I run that, the server is going to be powered. And you can see it's listening on this, the port is 3,000 on the IPv6, which is basically 127.0 and 0.1 in the IPv4, which is basically I have an alias localhost to that. So everybody probably already has that alias. But if you go to the browser and go to localhost colon 3,000, or you can type in the IP, you should see the Rails page like this. That tells you the version of Rails and the version of Ruby, the language. In my case, it's the Ruby language 3.3.2, okay? Yeah, so let's get started now and look at the structure. So there's a lot of going on here. As you can see, there's many directories. So all of these have follow-up convention that you just got to learn where things are and they'll always be that way. Just remember, convention of configuration from Rails. They asked gem install Rails still in progress, repeat the server command. Yeah, server command is basically CD to the project and then run Ruby space bin slash Rails space server. Now this is for Windows. If you're on Mac or Linux, you don't need to say Ruby. You can use forward slash, okay? Now if you go to, let me see, config slash routes.rb, by the way, if you're new to the Ruby language, the files in Ruby are written with the extension.rb. This is where the definition for the routes will be. For example, this one right here, what is it saying? Basically it's establishing a route that's going to be HTTP grad. Now they use it as a function call, okay? What is this meaning if you come from another language? It's basically a function call, the get function. You pass these arguments. Just telling, okay, if you go to slash up, I want it to show this particular function call, call this function here, okay? So let me show you in the browser. If I go to slash up, that's basically that definition. It's just a green page is saying, okay, the server is up and running, so it's green. Yeah, like I told you, the person who asked me about the command not working, make sure to CD first. You have to CD to the project. Like I told you, remember, right now you are in introduction to Ruby on Rails, but I think you've got to CD to whatever you used for the project name. In that case, it's intro to ROR, so you got to do CD, intro to ROR first before running the command Ruby bin slash Rails server. Make sure to CD everybody, CD, change directory, okay? All right, so how do we define our own routes? Let's start with a very simple one. Now the way people usually generate the files for Rails is instead of doing it by hand, they use a command. So to kill the server, you can press Ctrl C and it exits. Now you can type the command to generate what's called a controller because Rails uses what's called a model view controller approach. Let me show you that means. Basically you're going to run Ruby bin slash Rails. You don't need Ruby for a Mac, okay? And you're going to do generate, by the way, if you need help, you can just do dash, dash help there and it will tell you all the commands you can run. So I want to run this generate one. It has an ADSG if you don't want to type a lot. So if I run bin slash Rails, generate, and I want to generate a controller, okay? And I'm going to, let's make a page to show products of an e-commerce store, for example. I have products and I can create a new product that's going to be starting the database. So I can call this products like this, all right? Make sure to follow the same case. I put an uppercase P because Rails has very strict about everything. So if you fail to put singular or plural or maybe a case, it might affect the stuff. So just do it everybody like that. And then you can specify, let me see, what actions you want to, actions basically, okay, if I come to a website for products, we're going to have a page for the index listing all the products. We maybe click one product to see more information about that product, some details. That's the show action. And then if you need to create a product, that's the new action. And if you need to edit a product, it's the edit action. And you've got to follow all these keywords in Rails so everything works out of the bat. So that's the kind of thing that might be a nine to some people. You cannot just name it whatever you want. Obviously it could, but it wouldn't work out of the box some stuff if you name things differently. So I'm just going to add index here because I just want an index action and press enter. Now you can see what that does is basically it generates files. And the first file generates is under app slash controllers slash products controller. Do you see it always uses the convention of plural underscore controller. And if I click this file, it defines a class in Ruby. So Ruby is an object oriented language, OOP, object oriented programming. So if you wanted to find a class, you call class followed by the name of the class. And you make sure to put an end here. So you close the definition of the class. And you always use for Rails the convention of plural name, followed by controller. And this lesson sign here is inheritance, okay inheritance meaning this controller class will inherit from this application controller one, which is this one here. You see that one? This is the one. And this in turn inherits from action controller colon colon base. Now colon colon here is a way of kind of namespacing that, okay, or modular stuff. So you can see there's nothing defined between the class and end. Why? Because Rails already has everything written behind the scenes in the base class. So that's why it's abstracted away from you. So that's what some people, this is very hard to understand what's going on here. I don't see anything yet. There's so much magic in the behind the scenes making everything work as you're going to see later. It's because Rails already writes everything for you in the base class. Enough of that. Going back to product control, you can see I define here this dev keyword to define a function, okay? And then you have to have the end. If you come from Python, it's like Python, you would basically have a colon here and some annotation, right? But in case of Ruby, you have to have the end. And the function doesn't need the parentheses. That's what's kind of throws some people off. In Ruby, the functions don't, the parentheses is optional. So that's why you don't see it. So it's a function called index that belongs to the product's controller class. Therefore, you can call this a method. That's the name we use for functions that belong to an object. And you can see there's nothing defined. What the heck is going on? Basically, what's going to happen is, if you define a route in routes.rb that goes to this controller action, let's take a look at routes.rb. Do you see this part here? So if I, it already added that for us. So basically, if I go to product slash index, it's going to hit this function. This is like the handle function if you're express JavaScript and execute whatever this. Now Rails behind the scenes, it's going to render a template for you. And that template has to be under apps slash views slash products slash index.html.rb. You see the index word has to match this index here. Otherwise, it doesn't work. So this index was generated for us from the generate command. So if you didn't do the generate command, you would have to write everything by hand. You would have to create this file, products controller. You have to create the view file here. And so on and so on. Now, what is this file? Why is it dot urb? Because this file, we can kind of embed Ruby language stuff. It's called embedded Ruby. It's basically HTML, but you can add something more if you use the tags like this. You can use Ruby commands. But we're going to talk a bar about that later. So you can see it created kind of a scaffold draft page here and let's see. Let's bring the server back up. It created other files like test file and a helper. We don't care much about that right now. But basically, let's run the server again so I can show you the route being executed here. So if I go to slash products slash index, now I should see that page. What's going on here? Permission denied. There you go. I refreshed and it went away. I think it was something about a pre-compiling that crashed, but it's working now. So this is the page that we see in index.html.erb. And if you change that, it should change there. If I go app views, products slash index, let me put the paragraph here. Hello world and save it. It's just HTML, right? Save it. You can see these are the server logs here and they're very useful. You see this is the error that happens. Something about templating stuff, but eventually it worked and completed 200. Okay, in any case, going back to this, I can refresh and I should see hello world. Okay, so when you hit enter here in the browser, it makes a get request to this endpoint. Now Rails, you have to let it know in, let me see, config routes.rb. Because there's this definition here, it knows, okay, I have a get request to product slash index and that will go to product controller, call the function index, and this function will behind the scenes call to render this index file here. Okay, that's what's happening. Is everybody following so far? All good. No trouble executing things, installing. Let me know, okay, in the chat. I know it's a lot in the beginning, but once you get past that, it should go smooth. Okay, nice. So as you can see, we have a controller that's kind of routing and processing the stuff. And we have the view, which is actually what people are seeing. So model view controller is MVC, if you ever heard that MVC pattern, that's what Rails uses. Now we didn't talk about models, what about them? Now models, it has something to do with how you store the data. So here by default, Rails, if you go to config slash database dot YAML, it by default configures you here to use SQLite 3, which is a kind of implementation of SQL. And this one stores everything in a single file, you don't need to have a server. And this file should be, if you see here, this one, under store slash development, that's SQLite 3. So if I go to storage under the root, development SQLite 3, that's the database file. There's nothing there. So if you want to see what's in the file, let me open a new tab here. You can actually run database commands if you do bin slash Rails space DB. And that will power up the SQLite kind of command prompt. And I can type stuff here, maybe, let me see if it knows describe show tables, you see. That one doesn't work SQLite. I don't know what's the command, maybe I'll say dot help, and show you all the stuff. Dot databases, this is the one is SQLite dot databases. So I have the main one, which is this one. And let's see how can I show databases tables, this one, let me see, dot tables. So I have these two tables so far, okay. So this is the command line, you would pretty much run command like select star from schema migration stable, and it shows you there's nothing right now. All right, I'm going to exit, I think I'd say dot exit. That's the command line approach. If you're interested in SQLite, there's the graphical user interface program that I recommend. Is this one DB browser for SQLite, if you're ever interested in that. And I'm going to show you how I can use it right now. Basically this, it's not necessary, you can just rely on the command line. I have it open somewhere, hold on, DB, SQLite. One moment. Meanwhile, let me know if you have any questions. Let me just resize the screen so you can see better, share. This is what it looks like. The graphical user interface, basically click open database and you choose that file from storage slash development.sqlite3 and it shows you the tables here. Like we saw in the command line, there's two tables and you can right click browse table to see the data. There's nothing. I could go back database structure and the tabs here. You can modify the table if you want to add more stuff, tables, columns and so on. But everything that we're going to build, that's actually, we don't have to do it manually. We're going to do what's called a migration that will run the SQL behind the scenes. I just want to show you that for curiosity if you want to know more about SQLite. Anyway, let's go back. Okay, great. How about we store the products in the database? How would we do that? Well, we need, basically we need to create the table in the database. Now we can do that manually, but the way we do in Rails is we create what's called a migration. This migration is Ruby file that will define what the table will look like and it will be run and interface to the database and run the actual SQL. And after we get that done, we have to find a way to interface with the database through the Ruby language. And to do that, we use what's called the object relational mapper ORM. And for the case of Rails, it's called active record and it comes built in. And but to use that, we got to create what's called the model. Okay. Now, you don't have to know how to do it by hand. You can use a command like we did before to create a controller. Okay. So we can do then slash rails generate model and then you give it a name. It has to be like product like this single singular. And I put P uppercase there. And then after that, you can define the attributes if you want to do it now. For example, product could have a title colon and that the type string space. We can have a description and it could be string or it could be other very long tags without bounds. You can use stacks. Just for the sake of example, there are different kinds of data types. I put tax here, enter. And that should create the files necessary to hook up with models. You can see it creates the migration file under db, oops, slash migrate. And there's a timestamp followed by the description of the migration. It looks like this. Basically, it's sort of a class. You see class, enable the class, end. And this class has to inherit from active record, colon, colon migration, bracket 7.1. So that everything works off the bat. That's just the rails way. You've got to obey the rules. And then you define a function that could be changed or you could split into up and down function. But for the sake of example simplification, we use change here. And this change function will define some statements to create a table. So basically, you call the function create table. And you notice in Ruby, it's kind of weird. People might have a hard time. It's actually optional to have parentheses. So imagine there's parentheses there. You can add it. So you create the table function, you pass the name of the function, sorry, the name of the table, in this case, products. But notice this colon. What is the colon? That in the Ruby language, there's the constant of symbols. So you could have string, right? With double or single quote, or you could have symbols, which is pretty much what people will use in Ruby. Because some strings will convert to symbols anyways, might as well use symbol directly. And rails just works like that. Or create a table with the products, name products. And then this thing here is called a block. It's kind of weird. Basically, you call the function, you pass this argument, and then you pass what's called a block with this do and end. And this block is like a callback function if you learn JavaScript. Basically this function create table will yield to the block somewhere in its definition to execute whatever is defined in the block. So the block definitions between do and end, and if you need to pass arguments that this function might call the block with, you can put the kind of vertical bars and the argument name t. And then this argument, I think it passes like some sort of table builder, and you can call that object with these functions, like string, and you pass the name of the column that will be created. So this is basically doing, okay, I want you to create a column for the table products that is called title and the type is string. And the same way, okay, create the column description of type text. And then it also adds timestamps to basically, it adds the columns created underscore add and updated underscore add to keep track of when it was created, when the record was updated. And rails automatically changes those values for us. Okay, so that's the migration file. And after that, we got the model. So you can go to app dot slash models slash product, basically a class that inherits from application record, which is basically here, this one. And it's just a class that inherits from active record base. And this active record base will give us all the magic. Okay, that's why you don't see pretty much nothing is defined in product. You might be coming from other languages and think, how come we don't have to define the title, the description in the model? Because rails just does that, all those, yeah, that's why some people hate rails, because it is not explicit. You don't know what's going on when you read the code, all right? And that's basically it. And there's some other stuff for testing. You don't care about much right now. Okay, while we're at that, before create the user interface, we can actually use these models already. So I can do bin slash rails console. And this is very nice. It allows us to use active record, the Ruby language to interface with the database. And you're going to see this IRB interactive Ruby prompt. And we can just say the name of the class, which is product. And if you want to create one, you create an instance of the class. And to do that in Ruby, you don't say new product, you say product dot new. That's just the way in Ruby. And it's a function call, but you don't need a parentheses. So you can just call it like this. Okay, but you've noticed something happened there could not find table products because the table doesn't exist. So what do we do? Well, when you create a migration, right, the model in migration, it actually doesn't run the migration to create the table yet. So we got a call to run it. So let's go back and exit this control D. And we're going to do bin slash rails, dv colon migrate. And what this does, it will go through the migrations that have a net been run and run them. So it created the products table. You see that? Now how does it know keep track of all these migrations? How does it know it's run? Well, it uses the column schema migration. Let me show you here in the db browser, if you recall that, let me refresh. You can see there's products here. I don't know if it's, I can increase the zoom on this. I hope you can see it. Anyway, this table here schema migrations, if you browse the table, you can see now it added a new row with a timestamp. And this is basically saying that it has run the migration up to this point. And this point is defined by the name of the migration file, if you recall. If you go up, what is it? db migrate, sorry. See this timestamp? That's what keeps track of that table. So it knows it's already run. And enough said, you can see that the products table is there right here. See products? And if I expand, you see the definition of title description. And you see Rails already adds a primary key for us and already adds the timestamp columns. And we just had to do the title and description. If you want to know more about that table, you can modify here. And here's the SQL that was executed, right? This one. Okay, great. Now let's interface through this database instead of doing SQL commands directly. Let's use the ORM active record. So let's go here and go back to Rails console. Now we got products, right? If I do product.new, you see that creates a new instance of the product. Basically it's an object. If you know object oriented programming, we got a product class that can be used as blueprint to create many kinds of objects, many objects product, right? So product.new instantiates that. You can see Rails Ruby makes it really nice for us to visualize the properties here. It's a new value for ID, title, description, so on. Now this new is what Ruby uses for null value. If you're in JavaScript, it's called n, u, l, l, null. If you're in Python, it's none. It's basically nil in Ruby. Okay, now obviously we, it's gone now. I cannot reference it. I think maybe if I use this, it would reference underscore. Anyway, I got to put that in a variable. So we create a local variable called product equals sign. I'll take whatever I had before. And now when I save product, that's a variable that holds that object, okay? Now that's how we create variables in Ruby, just say the name equals n whatever value it is. It's like Python. Anyway, you might notice that Python, the language, is very similar to Ruby. So if you want to save this product, you can say product.save and that should save it. You see, it shows you the SQL that's generated by just calling that. Somebody asked, could you repeat the product generate? Yeah, so to generate the model, you can go like this. Let me copy and paste for you. If you're on Windows, you need Ruby bin slash Rails generate space model, space product of the capital P, space title column colon, string is the type, space description column colon, text is the type. That should generate the migration under db slash migrate slash the timestamp and the description dot rb, the model under app slash model slash product and other stuff we don't care about right now. And then after that, you got to make sure to run the migrations with this command bin slash Rails db colon migrate. I pasted the Zoom chat. All right, and then after that, you should be able to see this message. It's been migrated so you can open the console with this command bin slash Rails console. Okay, so we got product I saved it and see the SQL generated by that is this. And if you want to see all the records, you can say product dot all. And it will give you an array of product objects. You see that it even gives you the query that was used to get that. Product dot star from products table. It's very nice. I see if you need the first one, you can say bracket zero because that's an array. We access the first elements by saying scrap bracket zero. And then you can put that in a variable if you want another product or a reloaded product, whatever. And just keep going like that. Okay, so basically product dot new, put in a variable, change what if you want to change like the title, you can do the P dot title equals hello, like this. And if you see P, it's like that, but it's not yet saved to the database. You've got to say P dot save, like that. I notice it returns true if it saves, if it returns false if it doesn't save. Now in Rubyland, you're going to see this as well, P dot save bang, exclamation point. It's another method, which does the same thing, but instead of returning true or false, it throws or raises an error or exception if something goes wrong. So if you use that one, it works the same way. But if you had a problem like something is required, maybe, I don't know, how could I simulate that? P dot created at, let me see if this works. P has a no created at, can I do this? Dot save, there you go. You see what happened? It generated an error here, it raised no constraint fail because I set created at to nil, and it raised this constraint exception and it rolled back, it didn't save it. And if I had done with the P saved without this exclamation, let me see what it would do. Usually it's every turns false without throwing. I don't know why it's true, but anyway. How's everybody doing so far? Yeah, let me copy the commands for you again. Product equals product dot new, product dot save. Okay, so like I said, product dot all will give you like that. Yeah, all of them as an array. If you say product off first, it gives you the first one that it finds. If you give dot second, the second, you know, it's kind of weird, right? If you come from another language that has like words for methods that give you the first a second and all that stuff. Now, enough of that, let's work with the view. Let's go here. We're kind of running out of time. So let's show other products. So what we would do is remember we have a page under app views products index, right? Let's show other products here. So how will we do that? How can we access database from the view? So basically, you can you have to first usually what we do is we set an instance variable that can be accessed from view. So in the controller, under index, you're going to do the following. Let's first use product dot all that's active record that's going to generate a query to get all the products as an array and put that in a variable called products. But this variable, we need to access the value from the view. And to do that, you can make this an instance variable. If from object oriented programming, an instance variable is accessible from other methods, right? If you define it here to do that in Ruby, you have to do the at sign before the name of the variable. That way it's now the instance variable. Okay, now this is accessible from index dot HTML. So how do we reference here? Basically just say products like that. But we got to put it iterate over it. Do a loop, go over all the products and generate some information. So basically got to do these ice cream cones like this. Because if you type Ruby in the herb file, you got to use ice cream cones. So basically this dot each is the function I can call in the array. And this function expects a block. So I can do do and then product as the arguments of the block. And then I can just use product here like this with the equal sign. By the way, I use equal if you want to take the value from whatever you're going to type and replace in the HTML. Product dot title. To get the title and close it. And make sure to close the iteration of each with the end here with ice cream cones. And this should give a product dot title. Let me put in a div. You can put a div here. And the title is in a div. Like that. Let's see what happens. Save everything and let's go to the browser. Where is it? Refresh. I see hello there. That's the title. And we don't have styles. It's hard to know, right? But basically right click inspect. It basically generates a div with hello with the title. And there's a div here with nothing. It's because we had a product of an empty title. We allow that to happen, but we shouldn't. That's why it's like that empty. Anyway, you can go in the console here and get the first product, right? Set the title. Let's put in a variable P. P dot title is. Another thing P dot save that should save it. And if you go back, refresh, it should do another thing there. Okay. Okay, going back, let's make it prettier. I'll add a class here called product entry. How do you find CSS in Rails? Well, it's easy. Go to app assets, stylesheet, and then go to the app assets. Well, it's easy. Go to app assets, stylesheets, and you can just create one here called products.css. And you can type product entry class. And then I'm going to add some padding of 16 pixels. Maybe I would do a border on two pixel solid black so we can distinguish between them. And that's it. Very easy style, products.css. It's going to automatically be ingested by the pipeline. The rails pipeline there. And it just had a class. Let's try. There you go. That's the styling. If you want to add make them like separated, I can do that as well. I add a div in closing the whole list at a class product entry list. And I make sure to close the div here. And then what I do is go to product CSS. I add that product entry list and everything that's inside that with a class product entry. I want to add margin bottom 16. That way they have separated. Okay. And that way I got the separation. Okay, how to create a new one through the web interface. Let's add a button to go to the new page. So let's first create our own. So in the under product view, I'm going to add a new file called new.html.erb. Make sure it's new. Okay. And this page will have the form to create the thing a new. Now to work with this, I need a controller action. That's equivalent to show to render that. So go to product controller under controllers under the class. Under the class add another def. I usually like separated space. Exactly name new. Okay, like that. And it's a function. You don't need parentheses because Ruby. Okay. Somebody asked how did you create product controller? Yeah, I'll show you the code. One moment. Basically controller generate. Where's that? Where did we do that? We generate the model. Did I lose it here? This one. Let me copy and paste for you. That's the command to generate the controller. Anyway, going back. Basically create a new function here method called new. And that should render this new here. Okay. But the problem is this. Let's put here create new product just so we can see it working. Now if I go to the browser, right. And I say slash product slash new, what's going to happen? No route matches get slash product slash new. Okay. So we got to fix that problem by defining that endpoint. Then they see rails tells us what the endpoints are available here. So we got to go to that file under I think config routes. I'm going to add a definition here. Now there are different ways to define it. So it's a get request, right? And we want to do. To products new, right? So here. We can do like this, product slash new, that's the end point we can put the slash if you want. Now this is going to someplace. Now remember this is a function call. So I can have friends like this if you want, if it's hard for you to visualize. And the second argument I can pass like this a key. It's like a keyword parameter, but it's actually a hash. You got to learn Ruby. But anyway, just put two, you can say the name of the controller hash, the name of the function. So basically, okay, when I hit slash product slash new, I want this to be routed to product controller. And the method is new. The hash means the method. Okay. With that definition going back to the browser refresh, it should be able to see creating product. Okay, that's just the way the way rails work. You got to follow the rules and do it the way they want to make things work. Okay, now let's go back and define the new. So in this one, let me just put h1 there. And if I want a breadcrumb would be nice here. This is how you do comments, by the way. To do breadcrumb. If you want to comment something out is like this percent equal. Anyway, let's create a form here. So the way you can create a form, obviously you can do it manually with the form tag and everything, but rails has some helpers to help you out some functions. So you can do it like this. You can do a form with let me see if I get it right form with sometimes I forget the name of the function one moment. Let me see here in the docs. Yeah, form if it's correct and call this function with a symbol for the model thing. For example, model is whatever we're going to create in the controller. Now we got to define that somewhere. And then you close like that and you can define your thing. And I think I might need the equal sign here and then you can define all your fields here like first field for the title. Let's do and you've got a helper for that as well. Like with this form. Oh, by the way, this has a block that you can use this variable is an object for a form builder. So you can call that dots, for example, label to create a label element. And for let's see title, right? Like that. Let me just see right like this. It might be too hard to understand what's going on. So I'm going to complete the rest later. So to do make this work, we need this instance variable product. And to make that we go to the controller under products new, we create a new at product. And that's basically product.new. Create a new object and that's going to be used by that form with call. Okay, now let's go here to the browser to see if it's working. Okay, we got some error. Oh, sorry. I messed up here. It should be hash. Why did it put it equals? Sorry about that. The comment is hash, not equals. Hash, hash to comment. That's why it didn't turn green. The equals is when you want to interpolate or substitute whatever is produced by the Ruby code. Anyway, going back here, we got another problem. What is this? Undefined method products path instance. Huh. Oh, I know what's going on. Okay, so to make this work of Rails, it expects this products path to be defined. Now, this is a function that's used to produce, to give you the path to the route for the products. Now, to see what routes are defined in Rails, you got to call this command here. Let me put a new tab. Let me open it a tab here. And this command is called, by the way, somebody asked, where do you add the routes? The routes are added to routes.rb here. Okay, config slash routes.rb. Anyway, going back to what I was talking about, if you do bin slash Rails routes, this command will show you all the routes defined and there are alias, alias of path functions. Let me hide the thing so you can see. I'm going to scroll the way up and I want you to focus on this one here. That's, this is the alias, products index. That's the function that will be called to generate this. But Rails is expecting just products underscore path. This one is going to generate products underscore index underscore path. Okay, so we got to change this. How do we do that? Basically line two here. We got to change that to get products like that. And then comma two, products hash index. That way, when we do that and run the routes again, it will change that. If you scroll the way up, you see the prefixes products now. So Rails will call products underscore path. Okay, and that will work. Yeah, just the rail things. You got to obey the rules. You see, it's expecting this products path to be defined, but it isn't. Okay, if we do that, it finally works. Okay, it's kind of annoying. Anyway, you see, if I right click that, it generated a label, right? Automatically, just by calling form helper object dot label with the symbol for the property, in this case, title. Okay, now let's build the whole form. Yeah, I hope you can. After that, we can wrap it up. Anyway, go here, basically call more helpers, form dot tax field, and you pass the argument to this function called title. And then repeat, that's your description, like that. And instead of tax field, it's going to be, I think, tax area. Something like that, if I'm not mistaken. Yeah, all right. If you have trouble with the function calls, you can put parentheses, okay? It's fine as well. If you find it's very confusing not to not have parentheses. Finally, you got to add some submit button here. And you can do, I think, form dot submit, like that. There's no argument. And if you find this confusing, it's a function call. It's not appropriate. You can put the parentheses, okay? All right. And here at the top, some breadcrumb. Let's do that. Basically, kind of call the helper link to. And you can give a label like products, we'll appear, and the link will go to the products underscore path. So you can say common products like this as a symbol, and it will automatically go to products path. So let's write out, I got that, got everything. Now, to submit this, you got to create a new controller action here called create. And this control action, you got to make a variable. And you got to take what the user submitted from the form. That's going to be under params. But if you try to access it, like a hash or object in JavaScript, like this, it's going to be under a product. But it's going to complain, hey, you're not, you need to permit or whitelist the things. So to do that, you can do require as a function here, the product symbol. And then you can, you have to say, permit the title property and the description property. That's what we submit in the form. Finally, this will be the product params. Usually we call it like that. And we can do product dot new with the product params. And then we can do this, pass in, that's what the user submit, the title and description. And finally, you can put that in a variable and you can try to save it. Obviously, I don't have time through validation error. So if save will fail, we don't have anything right now. Okay, so you got to do that. And finally, after that end, and you can redirect if you want to redirect to the products index, same product symbol like that. And that's pretty much it. Let's see if it's working. We go here, refresh. We got the form, right? Remember, if you want to inspect and see what it generated, just click here in DevTools, labels and text areas. You see that everything's right. Okay, hello. Hello there. It's Rails. Create product. Oh, what happened? Something wrong happened. You know why? What did I forget to define? There's a file we have to define the routes. Anybody remember? It's the routes file. Okay, so I got to go to the routes file and define the, that's going to be a post, okay, to slash products. And that's going to go to products, hash, create. That way should make the form work. The route is now available. Let me try again. Hey there. There you go. Now we've worked and we got in here. Now, if you want to add a link to go to the new page, you can use the link to helper as well. Let's add that to the remember index app slash views products index. I'm going to add here at the top link to let's say new product. And then I'm going to go to products new. I think that's what it's saying here, right? Remember, look at this log for the Rails routes, products new. That has to match here. Finally, going back for refresh. I should see the link that goes to the product. If I click the breadcrumbs, it goes back. So it's working. Hello there, whatever, create. And I got to see the stuff there. And I think what's going on here? Let me see. This is title. This is description. I think I saw a bug or something. It's using description. So why is it using description? Basically, this one, you show description here. Or actually, this should be inside. What a div there. Div show the product description. Let's check the database because that looks very weird. Let's debug the database instead of the Rails console. Rails console can just do a product. All right, that works. If you want to do the Rails DB, you can go here and go Ruby, bin Rails. And I already saw the problem. It's probably my form. I put title instead of description, right? DB, I want to show you this just real quick. Select start from products. And I can see here. So I think my form, I swapped title here for description. That's why it's messed up. So I have to put description here. That's my bug. All right, so let's test it again. New product. This is the title. This is the description. And I should see this is the title. Question mark, yeah. And the description follows. Right. Okay. And yeah, with that, I finished this lecture.
No comments yet (loading...)
No comments yet (loading...)
Did you like the lesson? ๐Ÿ˜†๐Ÿ‘
Consider a donation to support our work: