2017-07-18 76 views
-1

我在Cloud9上開發了我的Rails應用程序。Rails:如何將頁面標題設置爲URL(路徑)

我想要做的是設置URL的標題的一部分,如stackoverflow。

(例如example.com/part-of-tile-here

雖然我找到了類似的問題,我不明白我應該做的,因爲他們中的一些舊帖子,在答題環節都沒有發現。 (例如Adding title to rails route

我現在不會使用Gem。

這將不勝感激,如果你可以給我任何提示。

回答

0

看看這Railscast這大致是你想要的。

TL;博士

你要保存slug這是一個參數化的標題,分隔由-當您保存頁面。 (在before_validationbefore_save

例如,「頁面的隨機標題」將得到random-title-of-page因爲它是slug。

before_validation :generate_slug 
def generate_slug 
    self.slug ||= title.parameterize 
end 

在頁面控制器,你就需要啓用由slug搜索。

def show 
    @page = Page.find_by_slug(params[:id]) 
end 
2

一般來說,何文是正確的,但是對於提出的解決方案有一些注意事項。

首先,你應該重寫to_param方法以及因此它實際上採用了毛坯:

# app/models/page.rb 
def to_param 
    slug 
end 

# ... which allows you to do this in views/controllers: 
page_path(@page) 
# instead of 
page_path(@page.slug) 

其次,你應該使用find_by!(slug: params[:id]) 1)是最新(find_by_xxxdeprecated in Rails 4.0 and removed from Rails 4.1)和2 )複製find的行爲,並在發現給定slug沒有帖子的情況下引發ActiveRecord::RecordNotFound錯誤。

第三,我建議要始終保持蛞蝓最新的,包括像這樣的ID:

# app/models/page.rb 
before_validation :set_slug 

def to_param 
    "#{id}-#{slug}" 
end 

private 

def set_slug 
    self.slug = title.parameterize 
end 

# ... which allows you to use the regular ActiveRecord find again because it just looks at the ID in this case: 
@post = Post.find(params[:id]) # even if params[:id] is something like 1-an-example-post 

如果你關心搜索引擎的結果,則應還包括在<head>部分規範網址和/或與控制器301個狀態,以避免搜索引擎重複內容重定向通常不喜歡:

# in the view 
<%= tag(:link, rel: :canonical, href: page_url(@page)) %> 

# and/or in the controller: 
redirect_to(post_url(@post), status: 301) and return unless params[:id] == @post.to_param 

希望有所幫助。

相關問題