Bacancy Technology
Bacancy Technology represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Riseâ„¢.
12+
Countries where we have happy customers
1050+
Agile enabled employees
06
World wide offices
12+
Years of Experience
05
Agile Coaches
14
Certified Scrum Masters
1000+
Clients projects
1458
Happy customers
Artificial Intelligence
Machine Learning
Salesforce
Microsoft
SAP
September 28, 2023
First, let’s establish the relationship between categories and books in the Rails model.
Make sure that the setup of models is like this:
Category Model
class Category < ApplicationRecord has_many :books end
Book Model
class Book < ApplicationRecord belongs_to :category end
With this setup, each category can have multiple books associated with it.
Fetching Categories and Books
Now, let’s move on to the controller. In the controller’s index action, we want to fetch all categories along with their associated books. To do this efficiently and avoid the N+1 query problem, we can use the includes method:
# Categories controller def index @categories = Category.includes(:books).all end
Displaying Categories and Books
In your view, loop through the categories and their associated books and display them as desired.
Here’s an example view:
<!-- Categories view --> <% @categories.each do |category| %> <h2><%= category.name %></h2> <ul> <% category.books.each do |book| %> <li><%= book.name %></li> <% end %> </ul> <% end %>
In this view:
Adding Links to Book Names
If needed, we can add links to the book names. We can modify the view like this:
<!-- Categories view for Book Names with Links --> <% @categories.each do |category| %> <h2><%= category.name %></h2> <ul> <% category.books.each do |book| %> <li><%= link_to book.name, book %></li> <% end %> </ul> <% end %>
Now, the book names will be displayed as links that lead to the respective book’s details page.