1 00:00:00,880 --> 00:00:04,900 Let's continue exploring the Rails console with create operations. 2 00:00:04,900 --> 00:00:08,910 We can create new records in the database by creating new model objects, 3 00:00:08,910 --> 00:00:12,370 setting their attributes, and then saving the objects. 4 00:00:12,370 --> 00:00:15,980 We can create a new post object by calling Post.new. 5 00:00:15,980 --> 00:00:22,940 So let's create a new post, and assign it to a variable, post = Post.new. 6 00:00:22,940 --> 00:00:26,810 Notice that the Post class name is capitalized whereas the variable name is 7 00:00:26,810 --> 00:00:27,700 all lowercase. 8 00:00:29,380 --> 00:00:32,690 You can see the objects we got in the Rails console output. 9 00:00:32,690 --> 00:00:35,960 Notice that its attributes are all set to nil. 10 00:00:35,960 --> 00:00:39,840 You can set the attributes the same way you would on any other Ruby object. 11 00:00:39,840 --> 00:00:41,781 Let's assign a title for this new post. 12 00:00:41,781 --> 00:00:47,706 We'll say post.title = "Hello, 13 00:00:47,706 --> 00:00:52,570 console!" And 14 00:00:52,570 --> 00:00:56,620 right now this object only exists in your system's memory, not in the database. 15 00:00:56,620 --> 00:01:01,960 If we were to call Post.all again on the Post class, It won't show up. 16 00:01:01,960 --> 00:01:05,465 To store it in the database, we need to call the save method on the object, 17 00:01:05,465 --> 00:01:08,550 post.save. 18 00:01:08,550 --> 00:01:11,860 Notice we're calling save on the objects referenced by the variable, 19 00:01:11,860 --> 00:01:14,190 not on the Post class with a capital P. 20 00:01:15,230 --> 00:01:19,637 We'll see an SQL query that inserts a new post in that the posts table with 21 00:01:19,637 --> 00:01:26,070 the title we assigned, INSERT INTO "posts" with title, created_at, and update values. 22 00:01:26,070 --> 00:01:30,210 And the value for title is "Hello, console!" just like we entered before. 23 00:01:31,690 --> 00:01:34,530 If we run Post.all again, this time we'll see that our "Hello, 24 00:01:34,530 --> 00:01:37,099 console!" post gets included in the results. 25 00:01:39,410 --> 00:01:43,220 Every model object you save to the database gets a value written to its ID 26 00:01:43,220 --> 00:01:44,670 database column. 27 00:01:44,670 --> 00:01:49,350 Notice that our post object didn't have an ID when we first created it. 28 00:01:49,350 --> 00:01:51,350 But now that we've saved our post object, 29 00:01:51,350 --> 00:01:54,740 if we look at it again, we'll see that it's had an ID assigned. 30 00:01:56,560 --> 00:01:57,680 As we saw before, 31 00:01:57,680 --> 00:02:01,290 you can pass an object's id to the find method to look it back up later. 32 00:02:01,290 --> 00:02:05,640 So if we type Post class.find and 33 00:02:05,640 --> 00:02:09,150 an ID of 4, there's our "Hello, console!" post again.