Rails: Working with Models
In this episode we show you how to generate a model. When generating a model rails will also generate a migration file, we walk you through whats in the migration file, we then move on to actually creating objects with the model and save it to the database.
# we can use this command to generate models in our app
rails generate model post title:string body:text
Once you run the above command it will generate a few files for you. The one to note is the migration file.
class CreatePosts < ActiveRecord::Migration
create_table :posts do |t|
t.timestamps null: false
Migrations only run once on a database. They help you maintain your database to ensure consistency across your development, and production environment. The timestamps will help us track when an object is created or updated.
class Post < ActiveRecord::Base
This is our first model. You'll see that it inherits from `ActiveRecord::Base` this is the class that handles all the interactions with the database for us.
To play around with the Post model we can boot into the rails console.
# this will put you into the rails console
We can create our first post with the code below
post = Post.create(title: "Hello World!", body: "Test Body")
# this will change the title of the object
post.title = "Change the title"
# this will persist the change to the database
# we can also create the post using
post = Post.new(title: "Another Post", body: "Another post body")