1

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?

cagliostro
  • 182
  • 1
  • 10
  • 1
    How are your models laid out? `Book has_many :chapters` and `Chapters has_many :titles`? with just `belongs_to`? – j-dexx Sep 10 '15 at 15:19
  • Thanks for your editing and reply. Models : Books : class Book < ActiveRecord::Base has_many :chapters end class Chapter < ActiveRecord::Base belongs_to :course has_many :pages end class Page < ActiveRecord::Base belongs_to :chapter end – cagliostro Sep 10 '15 at 16:48
  • Hi Cagliostro, and Welcome to SO. Can you please edit your original question to show your models instead of in a comment? It's much easier for us to read. – Daiku Sep 10 '15 at 18:24
  • @Daiku Sorry I m quite new here and I have still to learn how to ask correctly something, thanks a lot for your feedback. – cagliostro Sep 10 '15 at 19:37
  • No Worries, All Good! – Daiku Sep 10 '15 at 19:40

1 Answers1

0

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.

j-dexx
  • 10,286
  • 3
  • 23
  • 36
  • Super !! Great thanks to you. So has I don't still master yet Rails I have found this solution based on yours :
    `def show`
    `@title = Title.find(params[:id])`
    `@chapter = @lesson.chapter`
    `@Book = @chapter.book `
    `end`
    Cause Book was not recognised otherwise. Not sure to understand this line: `has_one :book, through: :chapter` but I will look in the rails guide, I have probably miss something in the association. Thanks a lot
    – cagliostro Sep 11 '15 at 08:54