DEV Community

Walktheworld
Walktheworld

Posted on • Updated on

Models, Views, Controllers Ruby on Rails Basics

I am currently working on my first Rails Application with a React frontend for my online software engineering program. My application is a Yelp/Untapped clone where a client/user can login/signup. Once that user is authenticated they can add a brewery to the database for any valid user to view and leave a review on. I was required to have a many_to_many relationship, so reviews is my join table in this instance. I wanted to share some of the basics of the MVC architecture.

Models

Models are in charge of all of the methods we receive through ActiveRecord association (ActiveRecord Associations and Methods). It handles all the business logic, dealing with state of the application. Here is an example of how your User model may look:

class User < ApplicationRecord

  has_many :breweries,  dependent: :destroy

  has_many :reviews 

  has_many :reviewed_breweries, through: :reviews, source: :brewery

  has_secure_password

  validates :username, presence: true, uniqueness: true

end
Enter fullscreen mode Exit fullscreen mode

Views

The Views are responsible for generating the GUI (graphic user interface) and presenting the data to the user.

Controllers

The controllers are responsible for the communication between the user/views and the backend. Talking through the models to sort the database and send back the appropriate view to the user. Here is an example of how your User controller may look:

class Api::UsersController < ApplicationController
  skip_before_action :authorized!, only: :create

  def index
    render json: User.all
  end

  def create
    user = User.create!(user_params)
    session[:user_id] = user.id
    render json: user, status: :created
  end

  def show
    render json: @current_user
  end

  def profile
    reviewed = @current_user.reviewed_breweries
    render json: reviewed
  end

  private
  def serialized_user
    @user.to_json(include: :breweries)
  end

  def user_params
    params.permit(:username, :password, :password_confirmation, :image_url, :bio)
  end
end
Enter fullscreen mode Exit fullscreen mode

I know how hard it can be to sift through the endless documents of info out there. I hope this helps you, as it did for me, retain some of the basics during your learning process.

Happy Coding!

Resources:
(https://guides.rubyonrails.org/active_record_basics.html)

Top comments (0)