KISS Model

nooope...!

·

2 min read

I am getting cleverer everyday with em titles.

Good evening!

If you read the rails guides at: guides.rubyonrails.org/getting_started.html

It says that Rails operate under two main principles:

  1. DRY - Don't Repeat Yourself
  2. Convention over Configuration

Once we start handling data in controllers we will slowly start to see this pattern to be present everywhere in Rails. EVERYWHERE!

It is so KISS - Keep It Simple & Stupid you'd be surprised how even a complicated action is so easy to write, execute and provide.

Let's start with the actions in our PostsController:

class PostsController < ApplicationController
  def index
  end
....
end

For instance, let's assume that we want to display all the posts created at our index page of posts.

In Ruby, we create instance variables using '@'.

class ClassName
  @object = "instance of the class"
end

Since we need to retrieve all the posts from the database we create write:

def index
  @posts = Post.all
end

There are many simple rules we must follow while writing any code. The naming convention must be on-point and easy to read for any developer looking at your code.

As you can see, we created @posts variable to retrieve all the posts from the database.

Notice carefully how we call it using,

Post.all

and not Posts.all.

In Ruby/Rails when we are dealing with Models(class) we use singular PascalCase styled variables.

Now before rendering it on the views, open the Rails console and enter Post.all.

rails console
>>> Post.all
>>> [...]

You will be returned with an array of objects. Each object holds the data related to each post created.

Now, let's try to find a specific post with a random ID numbered '3'.

rails console
>>> Post.find(3)
>>> Post [id: "3", attributes: ....]

Easy. Right!?

We didn't need to write a long SQL query to retrieve a post of id: '3'.

There are many pre-built methods offered by rails to query any specific object/data we need.

Refer to: guides.rubyonrails.org/active_record_queryi..

In the coming articles, we will talk about views and other actions and few more query methods in Rails.

Thank you so much for reading!

Ciao!

Love,

M.

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