Authentication and CRUD with Ruby on Rails

Ruby on Rails (RoR) is a powerful framework for building web applications. This tutorial walks you through creating an authentication system and CRUD (Create, Read, Update, Delete) operations in a Ruby on Rails application. By the end, you’ll have a functional application with user authentication and data management capabilities.

Prerequisites

Before starting, ensure you have:

  • Ruby and Rails installed on your system.
  • SQLite (default database for Rails) or another database configured.
  • Basic knowledge of Ruby and Rails.
  • A text editor or IDE, such as Visual Studio Code.


Step 1: Setting Up the Rails Application

Create a new Rails application:

rails new auth_crud_app --database=sqlite3
cd auth_crud_app


Add the necessary gems to your Gemfile:

gem 'devise'
gem 'sqlite3'


Install the gems:

bundle install


Set up Devise for authentication:

rails generate devise:install

Follow the post-installation instructions printed in your terminal, such as configuring your config/environments/development.rb and ensuring default URL options are set.

Generate the User model:

rails generate devise User
rails db:migrate


Step 2: Generating Resources for CRUD Operations

Generate a scaffold for a resource (e.g., Posts):

rails generate scaffold Post title:string content:text user:references

This command creates models, controllers, views, and migrations for the Post resource. The user:references part sets up an association between posts and users.

Migrate the database:

rails db:migrate


Update the Post model to establish the relationship with User:

class Post < ApplicationRecord
  belongs_to :user
  validates :title, :content, presence: true
end


Similarly, update the User model:

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  has_many :posts, dependent: :destroy
end


Step 3: Adding Authorization

To ensure that only authenticated users can create, update, or delete posts:

Modify the PostsController:

class PostsController < ApplicationController
  before_action :authenticate_user!, except: [:index, :show]
  before_action :set_post, only: %i[show edit update destroy]

  def index
    @posts = Post.all
  end

  def show
  end

  def new
    @post = current_user.posts.build
  end

  def create
    @post = current_user.posts.build(post_params)
    if @post.save
      redirect_to @post, notice: 'Post was successfully created.'
    else
      render :new
    end
  end

  def edit
  end

  def update
    if @post.update(post_params)
      redirect_to @post, notice: 'Post was successfully updated.'
    else
      render :edit
    end
  end

  def destroy
    @post.destroy
    redirect_to posts_url, notice: 'Post was successfully deleted.'
  end

  private

  def set_post
    @post = Post.find(params[:id])
  end

  def post_params
    params.require(:post).permit(:title, :content)
  end
end


Update the views to display user-specific content. For example, in app/views/posts/index.html.erb:

<h1>Posts</h1>

<% if user_signed_in? %>
  <%= link_to 'New Post', new_post_path %>
<% end %>

<% @posts.each do |post| %>
  <div>
    <h2><%= link_to post.title, post %></h2>
    <p><%= post.content %></p>
    <p>By: <%= post.user.email %></p>
    <% if user_signed_in? && post.user == current_user %>
      <%= link_to 'Edit', edit_post_path(post) %> |
      <%= link_to 'Delete', post, method: :delete, data: { confirm: 'Are you sure?' } %>
    <% end %>
  </div>
<% end %>


Step 4: Testing the Application

Start the Rails server:

rails server


Open your browser and navigate to http://localhost:3000.

Test the following:

  • Register a new user.
  • Log in and log out.
  • Create, edit, view, and delete posts.
  • Ensure that only the creator of a post can edit or delete it.


You’ve successfully built a Ruby on Rails application with authentication and CRUD operations. This foundational project can be extended with additional features like advanced authorization, file uploads, or API integration.  Hope this is helpful, and I apologize if there are any inaccuracies in the information provided.

Post a Comment for "Authentication and CRUD with Ruby on Rails"