Creating Simple Blogging Platform--Model
By: Lukasz Muzyka, On:
This tutorial assumes you have already completed:
- Install Ruby on Rails
- Create a Ruby on Rails application
- Create Static Pages - without this deploy will not work
- Install Git
- Create a remote Git Repository - optional but recommended
- Deploy application to Heroku
- Manage users with Devise
- How to add Twitter Bootstrap to a Ruby on Rails application - Advised
Let's make our website do something useful. How about building a blogging platform where users can share their stories. Our new web application will have the following features:
- All users can create, edit, and delete own posts
- All users can read other users posts
Step 1: Create "Post" model in Terminal
We are going to start by creating a new model for our posts. Open your terminal, navigate to your application. Make sure you type Post
in a singular form with a capital letter. It's a rails convention.
bash
cd documents/projects/demo
$ rails generate model Post title:string body:text
invoke active_record
create db/migrate/20140507054439_create_posts.rb
create app/models/post.rb
invoke test_unit
create test/models/post_test.rb
create test/fixtures/posts.yml
Step 2: Open Migration File
Same as when we were generating model with Devise for our users, we generated some files: migration, model and test files. Let's open migration first.
db/migrate/20140507054439_create_posts.rb
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title
t.text :body
t.timestamps
end
end
end
This migration file will be used to create a new table in our database to hold posts. Think about it as a spreadsheet that will have rows and columns. Each row will contain information about one post; each column will contain a different type of information about our post. Our posts will have a title which will accept data type of string (not too long set of characters, like a sentence in any language), body that will accept data type "text" (possibly very long chunk of text). Rails will also create two columns created_at
and updated_at
with the line t.timestamps
.
id | title | body | created_at | updated_at ------------------------------------------------------- | | | |
Before we migrate the database, we can still make the changes to this file. We can add, rename and remove fields. After we migrate the database - we can NOT. In order to change the database after the migration we need to create new migration file, otherwise we're just asking for trouble.
Step 3: Open Post Model File
Second file is the actual post model:
app/models/post.rb
class Post < ActiveRecord::Base
end
At the moment we only have opening and closing lines with no custom code in between. Soon, we will come back to this file.
Step 4: Run Migrate
For now, let's migrate the database. In terminal window:
bash
$ rake db:migrate
== 20140507054439 CreatePosts: migrating ======================================
-- create_table(:posts)
-> 0.0054s
== 20140507054439 CreatePosts: migrated (0.0055s) =============================
Now, our application has the ability to create posts and store them in the database. To see how it works, since we don't have any user interface yet, we will interact with the application through the console. Open a new terminal window, navigate to your application and run this command:
bash
$ rails console
Loading development environment (Rails 4.1.0)
2.1.1 :001 >
">" indicates that we are running Rails console. If you try typing bash commands here - they will fail. To exit console, either type "exit" or press "control + d" on your keyboard.
Step 5: Create a Post
Let's run some code in the command line:
bash
2.1.1 :001 > post = Post.new(title: "The first post ever", body: "Lorem ipsum dolor sit amet")
=> #<Post id: nil, title: "The first post ever", body: "Lorem ipsum dolor sit amet", created_at: nil, updated_at: nil>
We have just created a new variable "post", and assigned to it with "=" new instance of the Post. Post.new() - creates a new object in the memory. We can pass the parameters inside the parentheses, that will be used to assemble a new record. Notice that "title" and "body" match the names of the fields we have created when creating the model.
Step 6: Save Post
Also, you can see that the newly created model doesn't have an ID. When we ask for post.id, we get "nil" value. In our database, each record will always have an ID - it automatically creates a unique ID. Right now, record has an empty ID because it hasn't been saved yet. Method "new" only creates record in the memory and doesn't try to save it, therefore ID is not assigned.
2.1.1 :002 > post.id
=> nil
Let's save it:
2.1.1 :003 > post.save
(0.3ms) begin transaction
SQL (0.5ms) INSERT INTO "posts" ("body", "created_at", "title", "updated_at") VALUES (?, ?, ?, ?) [["body", "Lorem ipsum dolor sit amet"], ["created_at", "2014-05-07 06:44:22.227792"], ["title", "The first post ever"], ["updated_at", "2014-05-07 06:44:22.227792"]]
(0.7ms) commit transaction
=> true
Step 7: Check ID
Now, check if the ID is now assigned:
2.1.1 :004 > post.id
=> 1
Step 8: Create a new Post
Let's create one more post:
2.1.1 :005 > new_post = Post.new(title: "Second post", body: "Lorem Ipsum Dolor Sit Amet")
2.1.1 :005 > new_post.save
2.1.1 :005 > Post.count
=> 2
So we have a couple of records in the database already. Let's build a user interface to display those posts.
Comments
Comment
You can login to comment
On: Frank wrote:
On: Frank wrote: