2015-10-20 41 views
2

我有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 

其中name評論者=紐約時報

+0

如果你想寫你自己的方法:http://code-worrier.com/blog/custom-slugs-in-rails/ –

+0

如果你只想使用一個gem:https:// github的.com /諾曼/ F riendly_id –

+0

@LannyBose謝謝你的鏈接!正是我需要的! – fox

回答

1

你要查找friendly_id,有一個good RailsCast about it here

enter image description here


從本質上講,你需要的是能在你的系統來處理slugs

IE不是通過idprimary_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) 

這將讓路由與蛞蝓的工作,讓你打電話的喜歡:

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

+1

非常感謝,這正是我需要的! – fox

+0

Niiice!爲了將來的參考,你可能希望接受這個答案或其他人,所以人們知道哪一個是正確的 –

+0

完成,新的stackoverflow,所以不知道該功能存在。 – fox