Rails foundationSort Order

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 apprails 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  def change    create_table :posts do |t|      t.string :title      t.text :body            t.timestamps null: false    end  endend

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::Baseend

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 consolerails c

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 objectpost.title = "Change the title"# this will persist the change to the databasepost.save# we can also create the post usingpost = Post.new(title: "Another Post", body: "Another post body")post.save