Introduction to CRUD in the Rails Console
Hello, this is Andrew Perkins, and this is part two in creating a blog using Ruby on Rails. In this video, we're going to learn how to do CRUD: that's create, read, update, and delete. We're going to be doing it using the Rails console, so this will be done right inside of our terminal here.
The reason I'm doing this is it allows us to focus on doing CRUD in the simplest form without having to deal with any of web specifics such as redirecting or displaying error messages or creating forms. So let's get started.
Generating a Rails Model and Migration
First, I need to change directories into my blog application that we created in the last video. So that's under ror_tutorials/blog. And in here, we can run the rails generate command and tell it to generate a model, our Post model. We are using the singular form.
The naming convention is that your controller is in plural, which is posts, and the model should be in singular form, which is post. When this model was generated, Rails is also going to create a migration file to create a posts table in the database. A migration is a convenient way of interacting with your database using Ruby rather than writing SQL.
So when we generate this model, we can pass in some additional parameters to tell it what field should be created in that posts table. So we're going to want a title field, and we can put a colon and specify its field type. So the title field should be of a string type, and we also want a content field and that should be of type text. So we can run this command to generate our model and the migration to create our posts table.
Reviewing the Generated Files
And here's the migration file that starts off with a timestamp of when the migration was created. And then it's named create_posts because it's creating a posts table. It gets this name because of the name of our model. Our controller is plural, so it's posts, and the model is singular and that's post. And when we create the model, it's going to know to create our table in the plural form, so it's naming the table posts. It also created our post model here and a couple of test files.
Understanding and Running Database Migrations
So let's take a look at the create post migration in our text editor. Under the db folder, under migrate, this is where your migrations will be stored. We have our create_posts migration. It's just a class. It's really simple. Essentially what it's doing is calling this create_table method to create our posts table along with the two fields that we asked it to create: title and content.
Rails helpfully inserts this timestamps call to create two additional fields in the posts table called created_at and updated_at, and these will hold timestamps for whenever a post is created or updated. And Rails handles those timestamps for us; we don't have to worry about them.
So we can close the migration and we can apply it to our database. If we switch to our terminal, we can do that by running the rake db:migrate command. And Rails handles all of your migrations for you. You don't have to keep track of which ones need to be run, it knows to run the appropriate migration. So here we can see that it created the posts table and it says that it migrated, so it was successful.
Securing the Model with attr_accessible
Before we start interacting with the table, let's take a look at the model file that we created. So under the app folder, under models, open up post.rb and we can see it's a class called Post and that extends ActiveRecord::Base. This gives us a bunch of methods that we can use inside of our model. Now, we're not going to be doing too much here, but what we are going to do is clog up a potential security hole. Whenever we save or update posts, we're going to be doing this through mass assignment. This could be a potential security vulnerability where someone could access fields in your posts table that they should not be allowed to access.
So we need to tell it which fields are allowed to be saved via mass assignment, and we do that by using the attr_accessible method and we pass in which fields we want accessible. In this case, we want the title and the content fields to be allowed to be saved via mass assignment. And that protects us from that security vulnerability. So we can close the model and we can switch to our terminal.
Create: Adding New Records
And let's enter the, or start up the Rails console so that we can learn how to do CRUD. To do so, we run a new command called rails console, or you can run rails c for short. And that just takes a few seconds to load up. There we go. So now we can interact with our Rails console right here in the terminal. We can interact with our Rails application from right here within the terminal. We can actually interact with the database. We can write Ruby code.
So let's do the first part. We'll learn how to create posts. We can create posts in two different ways. First, we'll create a post variable, and this will be used to hold the post object that we're going to create. So we'll create a new post object, and what we pass in here is a hash. We can specify the title for the post and the content for the post. So we'll say the title should be Our First Post and the content should be Content for our first post. And this will create a new post object with that title and content that we specified. It actually has not been saved into the database, it's only in memory. It's just a post object. And we can see that it hasn't been saved because the id, created_at, and the updated_at values are all nil.
To save the post into the database, we can call the post.save method. This is why we created the post object inside of a post variable, and that's so we can refer to that post. So now it has a save method, so we can say post.save and that saves the post into the database. So we can pull that post object back up just by entering in post and we can see that it now has an ID field, it has an ID, 1, because it's the first post. And we have a timestamp for the created_at and updated_at fields now.
We can create a post all in one step, rather than splitting it up into two as we did here. We first created the post object and then we saved it. We can do all of this at once by using the create method. So we can say Post.create and then we just pass in the hash for our title and content of the post just like we did above. So we can say title and this will be our second post, and then the content 'for our second post', and hit enter. And we can see that that creates the post at the same time and that actually saves it. So we now have our second post and we can see that it was saved because we have an ID and it created at and updated at timestamps.
Read: Retrieving Records
Let's learn how to read or retrieve a post. So we can grab all of the posts. We can create a posts variable and we can use the all method to grab all of the posts. And that returns a hash of the posts in our posts table. We only have two at the moment so it returns the first post here and the second post as well.
We can retrieve individual posts. So I'll create a post variable and we can use the find method to find an individual post. What you pass to it is the ID of the post that you want to retrieve. So let's try finding the second post. It has an ID of two, so we can pass in 2 to the find method. And that retrieves the second post. We can retrieve the individual post's fields. So if we wanted to know the title of the second post, we can refer to our post object, so post.title, and that will bring back the title of the post. And post.content will bring back the content of that post.
Update: Modifying Existing Records
We can update a post. There's a couple of ways you can update. You can say post.title and we can just assign it a new value. So we can say 'our second post', and that changes it, but it's only changed in memory. When you do it this way, you actually have to say post.save and then that will update the posts for you and change the title in the database. You have to make sure you call post.save when you're just assigning it a new value.
We can also use something called the update_attribute method. And what you pass to it are two parameters. The first one is the field that you want to update, and the second parameter is the value of that field. So we could change the content and we'll set the content to be content for our second post, and run that. And you can see that you don't have to call the save method when you use update_attribute. It updates the table at the same time.
You can update all attributes if you'd like. You can say post.update_attributes and this time, you can pass in a hash and we can change both the title and the content of this post. So we can change the title. We'll change it back to what we originally had it, our second post, and the content will be content for our second post. And we can run that, and you can see it updates and changes it in the database back to the way it was. We can also look and see that the updated_at timestamp has changed. So if we take a look at the object, we can see that created_at time is different from the updated_at time.
Delete: Removing Records and Conclusion
Lastly, we can destroy posts. It's really simple. We have access to our second post here in the post object so we can say post.destroy. And that deletes the post. If we try to find it, we can say Post.find and remember its ID was 2. If we try to find it, we'll get a big error here. It's no longer available.
So that's how you do create, read, update, and delete. I hope you found this useful and thank you for watching.