Home > front end >  List sections with books associated with them
List sections with books associated with them

Time:10-08

I'm fairly new to ruby on rails and this has been kind of an interesting problem since this seems easy to implement in other languages but I don't know how to tackle it in this one. There was a similar post to this but it had two separate models which I would like to avoid.

This is my end goal:

Section Name

  • Book A, author

  • Book B, author

Section Name

  • Book C, author

  • Book D, author

Ideally, I'd like to have books be one model, so my model looks like this:

Book Model

class Book < ApplicationRecord
   validates :section, :title, :author, presence: true

Book Controller

def index
   @books = Book.all

I'm assuming I would need some sort of view that has it list it like below but I'm not sure how to go from there.

<% @sections.each do |section| %>
  <% Book.each do |book| %>
     <%= book.name %>
   <% end %>
<% end %>

Any help would be very appreciated!

CodePudding user response:

Firstly you need migration and associations between these models

change_table :books do |t|
  t.belongs_to :section, foreign_key: true, null: false
end
class Book < ApplicationRecord
  belongs_to :section

class Section < ApplicationRecord
  has_many :books, dependent: :destroy

And in view you can iterate through sections and separately through evert section books

<% @sections.each do |section| %>
  <div><b><%= section.name %></b></div>

  <ul>
    <% section.books.each do |book| %>
      <li>
        <%= book.name %>, <%= book.author %>
      </li>
    <% end %>
  </ul>
<% end %>

CodePudding user response:

what you need is this:

<% @sections.each do |section| %>
  <% section.books.each do |book| %>
     <%= book.name %>
   <% end %>
<% end %>
  • Related