Here is my route.rb:
resources :books, :path => "librairie" do
resources :chapters, shallow: true
end
resources :chapters do
resources :titles, shallow: true
end
resources :titles
Here's my models:
class Book < ActiveRecord::Base
has_many :chapters
end
class Chapter < ActiveRecord::Base
belongs_to :book
has_many :titles
end
class Title < ActiveRecord::Base
belongs_to :chapter
end
What I would like to do is choose a book in the library and see a page with all the chapters and titles (belonging to each chapter). This works. (library = AllBooks || Book#Show = Book with all chapters and titles)
Then, click on the title and get a page to see the text corresponding. This also works. (Title#Show)
Now I would like to add a button back at the top of the view of Title#Show with the following:
title of the book : chapter : title and with a link which go to the book (Book#Show)
However, after spending time in the controller I begin to be completely lost and my result looks worse and worse. How do I add such a button?
Ok, so you can do this
class Title < ActiveRecord::Base
belongs_to :chapter
has_one :book, through: :chapter
end
Then in your controller you can do
class TitlesController
def show
@title = Title.find(params[:id])
@book = @title.book
end
end
Which means in your view you can do
<%= link_to book_path(@book) do %>
<%= "#{ @book.title } #{ @chapter.title } #{ @title.title }" %>
<% end %>
I assume you're finding chapter in a before_action
here.