Ways of Creating Controllers
Creating a controller in ruby on rails is straightforward.
library\> rails generate controller Book.
We are here using the singular form and Capitalization of the Book. You should follow this whenever you create a controller in Ruby.
For creating a file, call the command app/controllers/book_controller.rb.
The controller's folder contains many folders, one of them being application.rb. The above folder contains an Application Controller file from which controller classes inherit.
The code that can run in every controller is in ApplicationController, which it inherits from the Rails ActionController::Base class.
Now define a few methods in book_controler.rb. It's totally up to you to name them, but it is better to use a relevant name. Your above file should look somewhat like this:
class BookController < ApplicationController
def list
end
def show
end
def new
end
def create
end
def edit
end
def update
end
def delete
end
end
Now, let's discuss the implementation of all the methods.
List Method
As the name suggests, this is related to the list. It gives you the details of all the books present in the database in the form of a list. To implement this method, write the following line of code in the book_controller.rb file:
def list
@books = Book.all
end
In the list method @books= Book.all line tells the rails to search each row of the books table for object instance and store them if it finds them.
Show Method
This method displays the details of the single book that the user has asked for. To achieve this functionality, write the following code:
def show
@book = Book.find(params[:id])
end
The line @book = Book.find(params[:id]) in rails will search for the book that has the id same as defined in params[:id].
We can pass the values between method calls with the help of the params object’s container.
Let’s discuss this with an example. Suppose you are on a page that is showing the list of all the books using the list method, and you want the details of a specific book, so you click on the link, and then you will get the id of the book by the params objects, and you will have your book by searching that id.
New Method
As the name suggests, we create a new object, letting the rail know that the user will create a new object. To make this method work add the following code:
def new
@book = Book.new
@subjects = Subject.all
end
This method will be called when you take user input from the displayed page. Here the second line takes all the inputs and puts them in the @subject array.
Create Method
If you remember, we have taken input from the user in the new method, but now we need to create them in the database. In the book_controller.rb, change the controller method to this:
def create
@book = Book.new(book_params)
if @book.save
redirect_to :action => 'list'
else
@subjects = Subject.all
render :action => 'new'
end
end
def book_params
params.require(:books).permit(:title, :price, :subject_id, :description)
end
@book is a new instance variable created in the first line that holds the book object from the user's data. We use the book_params method to collect all fields from the object:books. The new method passes the data to create using the params object.
Then, a conditional statement sends the user back to the new method if data is not saved correctly, and if data is saved correctly, it redirects the user to the list method.
The redirect_to method automatically and without any user interaction redirects you to your destination.
Edit Method
The show method and edit method are quite similar. Both are used to retrieve a single object from the array by its id and then display it on a page. But the only difference is we can't edit in the show method. The show method has the following code:
def edit
@book = Book.find(params[:id])
@subjects = Subject.all
end
To display the modified data by the user, we will call this method. All the subjects grabbed by the second line will be stored in the array named @subjects.
Update Method
We need this method after the edit method when the user edits the data. We need to save the changes in the database. The above method is similar to the create method used to update books in the database.
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 book_param
params.require(:book).permit(:title, :price, :subject_id, :description)
end
The save method used by creating and the update_Attributes method is quite similar but just a difference that it overwrites the current attribute instead of creating a new row.
Delete Method
As the name suggests, when user wants to delete a record from the database, then he should use this method as follows:
def delete
Book.find(params[:id]).destroy
redirect_to :action => 'list'
end
There are mainly two lines of codes first one finds the object by id via para and delete it from the database, while the second one returns the user to the list view
Additional Methods
Suppose you want the user to have access to all the books based on a given subject, then to display all the subjects, you can create a method inside a book_controller.rb.
def show_subjects
@subject = Subject.find(params[:id])
end
After adding all the methods, your book_controller.rb file will look like this:
class BooksController < ApplicationController
def list
@books = Book.all
end
def show
@book = Book.find(params[:id])
end
def new
@book = Book.new
@subjects = Subject.all
end
def book_params
params.require(:books).permit(:title, :price, :subject_id, :description)
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 book_param
params.require(:book).permit(:title, :price, :subject_id, :description)
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
def show_subjects
@subject = Subject.find(params[:id])
end
end
FAQs
-
Write some advantages of MVC?
There are many advantages, but some of them make the project more systematic, easily maintainable and manageable, classes and objects independent of each other.
-
What is redirect_to in controllers?
In controllers, it checks the request and redirects the user to a list view.
-
How does a controller connect models and views?
It connects models and views to make the model data available to view and display.
-
What are some drawbacks of using the MVC structure?
Some disadvantages are Multiple Technology required, complex structure, etc.
Key Takeaways
In this blog, we have learned what controllers in Ruby on rails are, their functions, and different methods like list, show, new, create, edit, update, delete, Display.
If you want to know about Views in Ruby on Rails, like what they are, how to create them, how to use them, etc. Then it would be best to refer to this blog here. You will get a whole idea about all this stuff and many more.