Rails Routes

no way...

·

2 min read

Hello children!

So far, we were successful in creating views, models and controllers for Post.

Now let's tell the application where to look when we input the url.

puma server usually runs on localhost:3000

# app/config/routes.rb

Rails.application.config.routes do
  # root refers to '/'
  root "posts#index"
end
# For basic and resourceful routing refer to: https://guides.rubyonrails.org/routing.html

The "posts#index" refers to the action index in posts controller.

This in turn routes the application to the page at:

# app/views/posts/index.html.erb

And we are shown all the posts on the webpage as we intended to do so.

Let's talk Validations.

"validate the state of objects before they go into the database...."

Since we are just storing a title and a body for a single post. We use basic validations such as,

# app/models/post.rb

class Post < ApplicationRecord
  validates :title, presence: true, length: { maximum: 20 }
  validates :body, presence: true, length: { minimum: 30 }
end

We write validations in the respective model file.

Above written validations simply verify that for any instance of Post:

  1. A title exists with maximum length of 20 characters.
  2. A body exists with minimum length of 30 characters.

While writing your :title and :body for @post in new.html.erb, if you don't follow these constraints Rails refuses the input and returns an ActiveRecord::Error.

There are much more items related to Routing and Validations and pretty much everything in Rails. And Rails makes it so darn easy for us to use it with their pre-built helpers/definitions/actions etc...

I will try my best to cover what I learnt and more whilst implementing it in my projects in my future articles.

Thank you for tuning in.

I'm out.

Love,

M.

liked_the_post == true ? comment and share : comment and share