top of page

How to store posts in database with Ruby on Rails

This post is going to walk you through how to add post information to a database in a Ruby on Rails application. This is likely relevant for you if the app you're building consists of a feature that allows visitors to create posts (like Twitter, Facebook, Google Reviews, Reddit, literally any forum, etc.) Unless you store each new post in a database, you won't be able to access that information past any given visitor's browser session.


The first step to storing post information in a database with Ruby on Rails is to have a basic Ruby on Rails application up and running. If you don't already have that, refer to the official Rails guides.


Okay, now to storing the post information. Something every developer who works with Rails needs to understand is that Rails follows the MVC (Model-View-Controller) architecture. This isn't as complicated as it might sound. Basically, the Model gets/sets information in the database, the View presents a user interface to the visitor, and the Controller (at the heart of it all) makes requests from the Model and invokes the View.


With that in mind, the first step to storing post information in a Rails app is to create a model. Rails makes this very easy for us. All you need to do is go to the command line and execute the rails generate model command.

rails generate model post title:string content:text time:datetime

After typing rails generate model, you need to provide a name for your model. This will also be the name of the table database object. Then, you define the names and types of the data your model consists of. These are equivalent to each column in the database table. Accordingly, the types (that come after each colon) correspond to SQL types. See below for the full list of possible types. The name for each column comes before the colon and is up to you.


SQL Data Types

:primary_key
:string
:text
:integer
:bigint
:float
:decimal
:numeric
:datetime
:time
:date
:binary
:blob
:boolean

Okay, great! At this point, we've generated a model for our post data. Now, we need to update our database with the new model. For that, we have a simple rake command.

rake db:migrate

Our new data model isn't very useful if we don't have a corresponding controller to interact with it, so the next step is create a controller Ruby file of the same name. For that, we can also use the rails generate command.

rails generate controller post

Awesome. You've now successfully created a database model for your posts and a controller to go with it. Jump over to your new post_controller.rb file under app/controllers/ and get coding!

Komentarze


bottom of page