Rails 4 带路由的深度嵌套

Rails 4 deep nesting with routing

这是我的route.rb:

  resources :books, :path => "librairie" do
      resources :chapters, shallow: true
  end


  resources :chapters do 
     resources :titles, shallow: true
  end
  resources :titles

这是我的模型:

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

我想做的是在图书馆中选择一本书,然后查看包含所有章节和标题(属于每一章)的页面。这行得通。 (library = AllBooks || Book#Show = Book with all chapters and titles)

然后,点击标题,进入一个页面,查看对应的文字。这也有效。 (标题#显示)

现在我想在 Title#Show 视图的顶部添加一个按钮,内容如下:

title of the book : chapter : title and with a link which go to the book (Book#Show)

然而,在使用控制器一段时间后,我开始完全迷失了方向,结果看起来越来越差。如何添加这样的按钮?

好的,你可以这样做

class Title < ActiveRecord::Base
  belongs_to :chapter
  has_one :book, through: :chapter
end

然后在你的控制器中你可以做

class TitlesController
  def show
    @title = Title.find(params[:id])    
    @book = @title.book
  end  
end

这意味着在您看来您可以做到

<%= link_to book_path(@book) do %>
  <%= "#{ @book.title } #{ @chapter.title } #{ @title.title }" %>
<% end %>

我假设您在此处找到 before_action 中的章节。