[Rails] Controller

Tags
Rails
Engineering
Created
Oct 18, 2023 03:26 AM
Edited
Oct 17, 2023
Description
Basic controller usage

Basic usage

After the router has determined which controller to use for a request, the controller is responsible for making sense of the request and producing the appropriate output.
  • ApplicationController inherits from ActionController::Base
  • Controller name using plural is preferred
    • ex: Books + Controller → BooksController
  • @var is accessible in the view
    • Same for ActiveAdmin
class BooksController < ApplicationController
	def index
		@books = Book.all
	end

	def list
		@books = Book.all
	end
   
	def show
		@book = Book.find(params[:id])
	end
   
	def new
		@book = Book.new
		@subjects = Subject.all
	end
   
	def create
		@book = Book.new(book_params)
	
		if @book.save
			redirect_to :action => 'list'
		else
			@subjects = Subject.all
			render :action => 'new'
		end
	end
   
	def edit
		@book = Book.find(params[:id])
		@subjects = Subject.all
	end
   
	def update
		@book = Book.find(params[:id])
	
		if @book.update_attributes(book_param)
			redirect_to :action => 'show', :id => @book
		else
			@subjects = Subject.all
      render :action => 'edit'
		end
	end
   
	def delete
		Book.find(params[:id]).destroy
		redirect_to :action => 'list'
	end
 
end

Source