[英]Custom URL Routing in Ruby on Rails
我目前正在用3.0學習Rails
我創建了一個帶有友好列的帖子表
我想使用/ post /:friendly而不是使用/ post /:id
表示網址看起來像/ post / post-title而不是/ post / 1
我已使用此代碼正確構造了控制器。
def show
@post = Post.find(params[:friendly])
respond_to do |format|
format.html
format.json { render :json => @post }
end
end
但是我不確定如何更改route.rb以實現此更改。
現在它只是說
resources :post
在此先感謝您的幫助。
您可以在模型http://apidock.com/rails/ActiveRecord/Base/to_param上使用to_param方法
如果將對象ID保留在友好的(例如1-some-name,2-some-other-name)內,則無需執行其他任何操作。 Rails將從字符串中刪除ID,並將其用於查找對象。 如果不這樣做,則必須更改控制器以使用find_by_friendly(params [:id])而不是find(params [:id])
另一種選擇是使用https://github.com/norman/friendly_id之類的gem來完成此任務。
如果要在find上更改id變量的格式,可以按以下方式更改路由
resources :post, :except => find do
# Change the find to accept an id that's alphanumeric, but you can change
# this regex to whatever you need.
get 'find', :on => :member, :constraints => { :id => /[a-zA-Z]*/ }
end
然后,要獲取帖子中的帖子#find,您需要
Post.find_by_friendly(Params[:id])
一個問題是,這將破壞助手路徑-例如post_path(@post)
將需要成為post_path(:id => @post.friendly)
http://guides.rubyonrails.org/routing.html#http-verb-constraints
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.