修改路线名称 - rails

Modifying route names - rails

我有 2 个模型(书籍和评论)和 2 个控制器(书籍和评论)。一本书有很多评论,评论属于一本书。

路线:

resources :books

在显示控制器中我有:

@book = Book.find(params[:id])
@reviews = @book.review

1) 这导致路由:

https://localhost:8080/books/1

我希望它是:

https://localhost:8080/harry_potter/reviews

其中书名 = 哈利·波特

2) 当我设置评论页面时,我希望路线为:

https://localhost:8080/harry_potter/reviews/new_york_times

而不是

https://localhost:8080/reviews/1

审稿人姓名 = 纽约时报

我一直在四处寻找,我想我找到了第一个问题的答案:

http://blog.teamtreehouse.com/creating-vanity-urls-in-rails

您需要查找 friendly_id, there's a good RailsCast about it here:


本质上,您需要的是能够在您的系统中处理 slugs

IE 不是传递 id (primary_key),而是使用另一个标识符(在我们的例子中是 "slug")来标识记录。

Friendly ID 促进了这一点——方法如下:

#app/models/book.rb
class Book < ActiveRecord::Base
   extend FriendlyID
   friendly_id :title, use: :slugged
end

这使您能够在控制器中使用以下内容:

#app/controllers/books_controller.rb
class BooksController < ApplicationController
   def show 
       @book = Book.find params[:id] #-> the route passes the "slug" as "id" still
   end
end

#config/routes.rb
resources :books #-> url.com/books/:id -> you can pass the "slug" to ID

--

您将 have to add a column 到您希望在 friendly_id 上使用的表(在您的情况下 booksreviews):

$ rails g migration AddSlugToBooks

#db/migrate/add_slug_to_books______.rb
class AddSlugToBooks
   def change
      add_column :books, :slug, :string
      add_column :reviews, :slug, :string
   end
end

然后运行rake db:migrate

之后(重要),您需要更新当前记录。为此,您应该使用以下内容:

$ rails c
$ Book.find_each(&:save)
$ Review.find_each(&:save)

这将使路由与你的 slug 一起工作,允许你调用类似的东西:

book_path("harry_potter")

嵌套资源

作为补充说明,您需要查找名为 nested resources 的路由原则。

使用这些,您将能够使用以下内容:

#config/routes.rb
resources :books do
   resources :reviews, only: [:index, :show] #-> url.com/books/:book_id/reviews
end

这将使您能够使用以下内容:

#app/controllers/reviews_controller.rb
class ReviewsController < ApplicationController
   def index 
      @book = Book.find params[:id]
      @reviews = @book.reviews
   end
end

因此您将得到以下结果:url.com/books/harry_potter/reviews