Creating a Post Resource in Rails
Walk through creating the Post resource for a Ruby on Rails application.
Guide Tasks
  • Read Tutorial

This is going to be a quick lesson, before reading through it I encourage you to attempt it yourself, the tasks are:

Use a resource generator for Post with the following attributes:
- title of type string
- content of type text
- A reference to the User model
- A reference to the Topic model

After running the generator and migration, you should be able to log into the Rails console and run something like:

Post.create(title: "Test", content: "Testing", user_id: User.last.id, topic_id: Topic.last.id)

This assumes that you have at least one user and topic in your database, if you don't have that add one before running that command

Resource Generator

Before starting let's make sure to check out work into a git branch and isolate it from the master branch until the post feature is completed, you can run:

git checkout -b add-posts

This will create and move us into an add-posts branch.

To get the resource generator working we'll start out by running the generator with the following parameters:

rails g resource Post title:string content:text user:references topic:references

As you may expect this will create normal columns for title and content, and it will create foreign key relationships to the users and topic tables.

After running rake db:migrate you'll see the new posts table in the db/schema.rb file. If you open up the models/post.rb file you'll see it also includes belongs_to calls to the User and Topic models well. To complete the relationship we'll need to update the other side of the relationship:

# app/models/topic.rb

# I've excluded the rest of the code in the class for brevity

class Topic < ActiveRecord::Base
  has_many :posts
end
# app/models/user.rb

# I've excluded the rest of the code in the class for brevity

class User < ActiveRecord::Base
  has_many :posts
end

I'm going to test this out in the console like I mentioned at the start of this lesson:

Post.create(title: "Test", content: "Testing", user_id: User.last.id, topic_id: Topic.last.id)

That all worked perfectly and gave me the output:

=> #<Post id: 1, title: "Test", content: "Testing", user_id: 3, topic_id: 4, created_at: "2016-02-16 22:31:53", updated_at: "2016-02-16 22:31:53"> 

Your values will be different depending on the user and topic IDs that you created last in your local database. Let's also make sure the relationships are setup properly, the following commands should all work properly:

Post.last.user
Post.last.topic
Topic.last.posts
User.last.posts

Nice, those are all working properly, so our Post resource has been successfully created and is working with the right database relationships. In the next lesson we'll go into how to nest posts inside of topics.

Resources