Hogwarts On Rails - Part 1

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
and then I'm just gonna sketch out what I want to build today and my font a little bit bigger no I refuse to use a strange font I just increased the font size and so what I want to do today is build a start building a rails application that will sort of show off how from the ground up to build an application that includes a bunch of different models and models that have some associations between them and so we're gonna go to the land of Harry Potter and we're gonna model Hogwarts on Rails and we're going to build a website where we have a model for a house and a house is going to have a name and that's going to be a string and a house is going to have some points associated with it which is going to be an integer and then we're also going to have a student model where a student has a name which is also a string and then a student is gonna have a reference to house there's gonna be a foreign key reference and so students gonna have a house ID and that's gonna be a foreign key to the houses table and so if you remember how active record works the house model will be associated with a houses table and the student model associated with a student's table and then the other things that active record will add into those tables which is like every one of these tables will just automatically get a primary key called ID and then they will both also get the timestamps so they'll get like it created at time stamp and a updated and I'm stamp both of them this one and this one so that's how we're gonna start things off today is I'm gonna create a new rails project for Hogwarts and then we're going to first create the house model we want to do the orders going to be somewhat important if we tried to create the student model first it would be hard to set up the foreign key to something that doesn't yet exist right because students are gonna belong to a house so I will set up the house first signing it name and points then I will set up the student giving them name and a reference to the already existent house from that point I'm gonna make a very simple seed script and a seed script is just an active record script that's going to put a bunch of fake data into my database and then we're gonna work at creating some more of the website of things so we're gonna start just in model land where you sort of are right now with the most recent challenge that you've been working on and then we're gonna step out of the models and make a controller and some views to start actually you know producing HTML that will pull data from these two tables so that is the goal and it's all gonna start by me going to my full stack folder where I put my rails applications and I'm going to run a command here just the rails command to create a new rails website and I'm gonna call it hog parts that's gonna go and do what you saw the rails new command dude the last time we went through it which is it starts off by if I scroll up to the top here creating a bunch of files and folders so that every rails project is the same directory structure it's going to initialize our project as a git repository does it get an init on the current working directory it's going to put into the root folder amongst other things a gem file and then the project will run bundle install it'll then load up all of the gems that are required and after that it's going to run a yarn install because in the root folder there's also a package.json file which is the JavaScript sort of equivalent of a gem file right that's where all of our JavaScript dependencies are going to live so that's what's running right here this is yarn install running the JavaScript dependency installation so that's gonna take a little bit of time to render out so I will go back over here and talk a little bit more about what we're going to do after we create those two models so I want a website where initially I can go to a page and I can see all of the houses in the school and the number of points that students have accumulated for those houses and so I'm gonna create a controller and it's going to be a houses controller and that's controllers going to have at least initially two actions and in rails actions tend to fall into two camps one camp our collection actions and those have to do with sort of the table that the controller is associated with as a whole and so we're gonna have a action called index and that's going to like show all houses and then there's also gonna be a member action which is just gonna be show and this is gonna be a charge of showing one house by ID rails has finished doing its thing just in case you're quoting along and you're still checking away there I'll give us a few more moments what I want from a routing perspective because remember we're dealing with like an MVC system here so the M or model we've discussed above here the C is just currently gonna be one controller the house is controller for the routing so the routes I'm gonna set up the fact that a gap requests just to the root folder or the root path of my domain so just in my case it's gonna be up on localhost which is gonna be when I do localhost 3000 I get requested that I want that to go to the houses controllers index action and I get requests to get requests to slash houses slash some ID and this is just me putting in like a placeholder for some numeric identifier I'm gonna want that to route to the houses controllers show action so that's how these two actions are going to be stitched up to connect to HTTP endpoints and then in terms of views there's going to be one view associated with each one of those things and so we're going to have views specifically we're gonna have a in the app views houses folder and index.html ARB that's gonna map to this action right here and a show on HTML the DRB and that's gonna map to this action right here I mean the only other bit of quote-unquote wiring that's gonna exist in our is this route here that has this ID placeholder here that's going to be how this show action knows which house to load by ID any questions so far about sort of what we're planning on building here does this make sense so so does everybody know Harry Potter is there anyone in the room that has not seen a Harry Potter movie or read a Harry Potter book for real so do you know what I'm talking about then in terms of like houses and students kind of so like just just for super clarity wizards and witches go to Hogwarts and then they're assigned to a house which is like they're going to school they sort of go to this house which is sort of their their like it's like a cop house they're part of the gang and then they have to sort of what they do the teachers give them points and so there are accumulating points for their house or sometimes losing points for their house and that's gonna give us our relationship so a student is gonna belong to one house in one house only and a house is going to have many students so there's a one-to-many association between those things and I highly recommend reading the Harry Potter books what is the oh the the creation command sorry that was just rails new and then it's always just the name of the project that you're creating right on so the plans are ready to go we are going to navigate to that folder that I've just created which is the Hogwarts 2020 folder and in vs code in my explorer here I'm gonna add that folder as well so I'm gonna go to the my amount C full stack go to where I put my rails apps and then pull up the Hogwarts 2020 folder and there as well and that gives me the ability to see the folder structure and then just a quick recap of like the folders here that are important there is a app folder and this is where our MVC stuff goes so our models are going to go in this model folder our views are gonna go in the view folder and our controllers are gonna go in the controllers folder so the MVC stuff all lives inside of this app folder the routes which is sort of the the missing letter from the MVC acronym they exist in this config folder in a single file there's a routes to Darby file in that config folder the other folder we'll be working with today will be the DB folder that's gonna be where our database seed script is gonna be written that's gonna populate our database and then our sequel Lite database file is actually going to be in this DB folder and then these sort of incremental changes that we make to the database are gonna be captured in this folder as well as what are called migrations so there's gonna be a migration folder in here the other thing we're gonna be doing is we're going to be using git to capture the changes over time to this project and so this project is a git repository it has no commits to it yet and I can commit to it either from the command line or just with the built-in tooling in vs code so there's the source control option here it's showing me all the outstanding files and folders that haven't yet been captured and so I'm just gonna commit those all right now as the initial commit so you could do this from the command line we could do like a gift add dot and then again commit - em with some message but more often you'll see me just using this code sometimes if I just anivia the terminal I might do the kibitz there but I I typically do it from vias code these days so I'm just gonna say initial commit of our Hogwarts rails project and then if I hit ctrl enter it'll say do you want to stage everything there and commit it and the answer is yes I do and now you can see my prompt is picked up like there's at least one commit I'm on the master branch and there's no outstanding changes I usually have three different terminals running so one of those terminals will be running the rails server so this is the rails HTTP server with the current version of rails it's an application called Puma and it loads itself up on port 3000 and so I've run rails space s or you can even type out the full word server rail space server and once that is in place I can go to localhost 3000 and just see that things are things are operational so say you're on Rails this has been served up from that Puma server on port 3000 we're gonna eventually remove this little welcome message but it's there right now and if we look here and where I ran rails s every time we interact with the server we're gonna see that interaction happen here so you can see that that index was the Welcome index is being loaded so I'm gonna click this little plus button here and open up another terminal and then this one I'm gonna run the rails console which is a version of the interactive Ruby prompt so it's a little command-line repple or I can type in Ruby code and it'll execute it the nice thing about the rails consoles though it's also gonna give me access to my models and so I can interact with the models and then through the models interact with the database here then I'm gonna open a third bash prompt and this is just gonna be for me running other rails commands so if we look at our plan the plan was to start with the models here so I got some models being created specifically a house model and a student model I'm not going to do what I did in the first rails demo where I use scaffolding instead I'm going to generate the pieces one by one so scaffolding went and created the model the view the controller the routes everything all at once here I'm in a sort of piecewise cuz I don't need everything I don't need a full front ask I only want really two actions two routes two views so I'm not gonna use scaffolding here sunlight scaffolding is just a little too much and so I'm gonna do a rails g4 generate and then what do I want to generate it's not a scaffold this time instead it's a model specifically the house model and we said a moment ago that a house has a name and a certain number of points so I can say name : string and points : integer and so when I run that it's gonna do a few things for me one it's gonna create a migration and a migration is a description of a change to the database and then it'll also create the model for me so in the app models folder it's gonna put a house dot RB file and so you can see here's the migration to put into the DB migrate folder and then there's the model we can go we can go see them here and pull them up in the app Adil's folder there's the house model empty right now we're gonna put some stuff into it in a moment and then in the DB folder we can see in the migrate folder right there we've got a migration that describes in sort of Ruby code the changes that are gonna be made to my database the change here being that we're creating a table called houses and a columns that exist on it and the reason why these migrations are super handy is that they are now part of source control and so if we were working with a large team everyone would see a new migration appear in the repository and everybody could run this migration and the whole team could synchronize their databases so we're gonna do just that right now we're gonna run the migration and that's where the rails DB : migrate and your travels on the internet you might sometimes see people reference rake DB migrate it's exactly the same thing so the DB migrate task runner looks in that migration folder looks for any migrations that haven't yet been run and it runs them if I tried to run it again it would know that there is no more new migrations to run so writing it a second time doesn't do anything at all if you're like me your WS L will or rails or something will constantly warned you about this insecure your world writable directory it's just a warning it doesn't actually mean anything's wrong I've tried to get rid of it in the past and I haven't been able to and so I just ignore it it hasn't affected my rail sites at all so after running that command we can actually switch over to our interactive Ruby prompts and if we run reload it'll reload any of the models that's in the model folder and I now have access to those models so I could say like house dot new and it'll be like Oh a house has an ID and a name at some points and created at and updated at and that's exactly what we want it to have so that's good I mean further I could even start creating houses here right I could do a house create blood and claw that's a Harry Potter house right and as a lot of points Oh what if I done wrong I didn't put the points in there I have to actually say what these things are so when I create I have to say like this is the name and these are the points and then this create statement here translates into a sequel insert statement so I now have direct access to my database by way of my model okay so I can go back to my source control and I can say created house model and man associated migration one of the things I try to do when I'm demoing stuff in class is I try to I try to model like good get practice like I'm see me trying to capture like incremental commits over time and I'm trying not to lump together a bunch of changes I'm trying to sort of make them small and self-contained and well explained in the commit messages but because the apps I'm building aren't like real production apps and I'm just sort of like effectively making little toy websites the the thing I'm not doing that I would say would be best practice for git commit messages is when you see me type of git commit message I'm usually describing the change that I just made which isn't very helpful for a get commit message because that information is already in get I get captures the changes over time so anyone looking at a get history will always be able to see what change at any given commit cuz they can look at the deltas but you can go on github and click on a commit and you can see exactly what changed so a good commit message doesn't actually describe what changed it should describe why you made the change now for me why I made the change is like I'm giving a demo in class right so it wouldn't be interesting for me always just type well I made this change because you know that's the next thing I'm doing in class but in an actual work environment if someone's looking back at it history they usually want to see what your intention was because they're probably looking back to figure out why a change was made or why a bug was introduced or why a decision in the code was done the way it was and so if you write your did commit messages make sure you're always putting your intention in there and not something like what was actually changed because the tooling already knows that and can supply that to the user all right that's that's this first thing done we've created our house model the next thing we want to do is the student model and this is going to have the reference to the house it's going to be the one to many Association so I'm gonna go back to my bash prompt here and I'm gonna do a rails generate model what am i generating well I am generating a student model where a student has a name which is a string and in this case to make the reference to house I just write the name of the model that I want to reference and I explain that it references so rails generate model the models name a student a student has a name which is a string this will become a varchar' in the database and a student references a house and that means that it'll have the foreign key so there'll be a house ID assigned to student so I can hit enter now on this command and just like the other rails G command it's going to create for me a migration this one right here and a student model so I'll close the old migration and open the new one up here's the new student model here's the new student migration here you can see in the migration it's describing the change that's being made the changes that we're creating a table the name of the table is students a student has a name column and a student references a house this reference cannot be no and this is a bit of a gotcha with I think it's specifically with sequel light 3 one of the things we'll see with migrations is sometimes you don't know everything about your database to begin so we could have potentially created the student stable and then realized after the fact Oh a student should reference a house with sequel light having a reference added after the fact to a table with null set to false will cause problems and the migration won't run and the fix is just it's a bit of a cheap fix is to set that to true meaning you could allow nulls in there and then sequel a will process it when we then actually go to production and run this on Postgres Postgres won't have a problem with a reference added after the fact with noah being false but that's just a bit of a gotcha that we're when we're working with sequel Lite I find that happens often so we'll leave that for now because this is not after the fact this is at the time of creation so sequel Lite will be okay with no Nell's on that reference and then specifically this is going to be a foreign key so we're gonna have an index on this key created as well so when we want to run this migration we go back to our bash prompt and we run rails DB I agree we'll give it a moment and we get our student table if we look at the model because when we generated the student we explained that a student references a house rails is put in there the little helper method that belongs to this sets up the Association so but we have to put the Association on the other side of a connection here which is in house so a student belongs to a house and a house has many students plural and again this is where pluralization becomes really important sometimes when people are new to rails they don't know if you know should this have an S on it shouldn't it have an S on it if you say it aloud like if you say the sentence out loud it should sound grammatically correct right a student belongs to a single house right because the student is the one that has the foreign key you wouldn't say houses here because if you if this is the table that has the foreign key you can't belong to more than one house so a student belongs to a house and on the other side a house has many students and it wouldn't make sense grammatically to say has many student and so if you're ever forgetting the pluralization there just say it out loud and it'll hopefully help you figure out if you need the s on the end or not so with those two associations in place that has to and belongs to or has many and belongs to we can go back over to our rails console here any time I make a change or an addition of a new model or a change to a model I have to run reload what I should now be able to create students and associate students to houses and so I already have a house in the system which is the glutton claw house that's the first house and so to create a student associated with that house just to make sure that this is actually working properly I can say glutton claw dot students dot create and I can say Walley glutton is the name of a student that belongs to that particular house and boom that creates an insert statement we get a new student object the student has been added to the database they have a primary key of one a name of Walley glutton which is what we asked for they've automatically been assigned to the house that created them so glutton claw had the primary key of one so the foreign key on the student gets that value because we were created through the house and then they created at and updated at timestamps are also fed up and it should work in the reverse direction I shouldn't just be able to go from a house to students I should be able to go from a student to a house so if we found Wally by finding the one and only student in our table I should be able to ask for Wally's house name and I should see the house associated with Wally and there it is so that proves to me that things are working and that's typically why I keep a console operational at all times in my rails app because I don't like to code too much without at least manually testing something if I was developing this for contracting purposes I would probably be developing a test suite like test-driven development style and so that would be how I was doing my testing but because I don't have a test suite here I'm sort of manually checking my assumptions as I go and so how are we doing is just anyone need to see anything that I don't have up on the screen or is anything not working the way that it's working on my machine but on your machine is something else anyone Keegan you look at liking you're struggling with something maybe oh okay no worries we can talk about that after cool so that's that's coming along that means we've done all of our model stuff alright we've created the two models that we wanted to have in place we only have an hour together today so we're probably not going to get to the controller routes and view stuff but we can get to the the data creation stuff we can create a scene script to populate our two tables with actual contents and so I'm gonna just quickly go to get and commit so I'll just say model with an association house I was in model and before I go and write my seed script it'd probably be nice to have a few validations on both of these and so I tend to put my validations below the associations so I'm gonna say that a student will validate if the name as a presence of true that's the only validation I'll put on there there's sort of an undefined or implicit validation in that the foreign key is also required and that's because when we set up that migration we saw that no was false right so I can't create a student without a foreign key so there's an implicit validation that we cannot create students that have no house Association and then over on house here I'll say that both the name and the points are required so I'll say validates name points presents true and then I'll say validates points numeric tality only integer true and I think that said I'm IRA constantly go back and forth between thinking it's integer only or only integer but that's just a quick visit to the guides away so if I go to my validation guides I can look up numeric ality and it is only integer true so I got it right this time so it's good I've got my my validation set up I can add those in to get at a validations and I'm gonna go to the DB folder and that's where there's this seeds dot RB and that's the place where we code up any bit of data that we want to exist in our database and you can run this script by running a rails command so I'm gonna remove the comments in there but I put a little comment in here by myself run this script using rails DB seed and the only thing that's a little bit awkward about this is that the file itself is called seeds with an S but we run it with a rails DB seed singular and that's just a quirk that's just the two aren't set up in the script we can detect what mode when we can tell if rails is in like development mode or production mode so we could have the script do one thing and set up the database in one way when we're running in development mode with maybe a bunch of fake data and then in production mode we could have it set up with like maybe your your app needs a little bit of data you know anytime you deploy it you could have that in the seed script as well I'm gonna create fake data which means I need access to fakir and so for that I'm gonna go to the gem file and right around here before we start getting into like gems that belong to different groups I'm just gonna put gem Baker this will just pull the most whatever the most recent version of faker is from the Ruby gems website which is slightly different than what you did on the challenge which is it pulled it directly from github and then to be sure that this actually now gets pulled into my project I have to from my command prompt do a bundle install which just checks to see if all of the gems are present and will now see faker in this list here so now i now have faker in my project so it's important to remember now that we're we're working within rails so we don't have to do some of the extra stuff that you had to do on the challenge or that you saw me do when I was covering active record outside of rails there's no more need to load up active record there's no more need to load up faker with require statements or an AR dot RB script or anything like that I'm my environment is already set up for me in the context of this seed stud RB script so I should be good to go to start creating and so I could create a certain number of houses so I'll say like number of houses maybe that's a constant so I'll say like number of houses equals and then I'll set that to like five and I'll say like students per house and I'll set that to maybe I'll set that up within a loop because I'll make it a little bit randomized so that there's not always the same number of students per house and so then I'll say number of houses dot times du and inside of here I'm going to create a bunch of houses so I'll say house dot create and I'm going to provide a name for the house and some points for the house and then have a house name it's gonna be something from Baker and then I'm gonna have house points and for this faker can't generate random numbers but it generates them as strings so I'm just gonna use the random method to generate and I'll say house can have any number of points somewhere in the range of 333 to 9999 it's a big range of points and then I'm gonna have to figure out which module in faker I want to use and for that I gotta go to the docks so I'll just say gem acre and I will go to movies and Harry Potter and it is this what I want right here most and we know that if I want to be sure that the thing that fakers generated is unique I can ask for a unique of whatever I'm doing and so the last thing that I will do today is just set this up so that it's gonna take that house name for the created house name and these house points for the created house points and then down below here we will maybe I'll even yeah I'll just say created just as a smoke test just to make sure things have working we have worked properly I'll say Oh Scout houses and that way when we run this script if we see that it created five houses we'll know that it probably did the right thing so that's the last thing we'll do today is just run this script it should loop five times picking a unique house name each time a random number of points and creating those houses so if I go to my command prompt here and I run rails DB seed give it a moment it'll tell me how many houses it has created created six houses oh and that's because I had one in there already so I lied I'll do a little bit more the very last thing I'll do is just make it so that every time we run this script it sort of starts from fresh so that we can run this script over and over and over and we're not accumulating more and more data over time that every time we run it it'll just wipe out the data and recreate it so run this again why you do that OMS because I have students just my test data that I had in there I can't have orphan students right if I destroy the houses there could be students that have foreign keys to houses that don't exist anymore so that's one final step final final step run the script five houses are created if I poke into my console I could say house count it's a house dot all there's all the houses hufflepuff is house number seven and next class we will continue updating the script so that we can create students for our houses and then we'll actually get into creating a web view for these houses with the controller and the routing system and the views coming into play thank you very much folks for coming to class today and learning a little bit about rails and Harry Potter
Info
Channel: Kyle Geske
Views: 617
Rating: undefined out of 5
Keywords: Ruby, Rails, Ruby on Rails, Rails 6
Id: EqtvG1Q1_zw
Channel Id: undefined
Length: 42min 24sec (2544 seconds)
Published: Thu Jan 30 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.