[英]Custom URL Routing in Ruby on Rails
I am currently learning ruby on rails with 3.0 我目前正在用3.0学习Rails
I have created a post table with a column called friendly 我创建了一个带有友好列的帖子表
Instead of using /post/:id I want to use /post/:friendly 我想使用/ post /:friendly而不是使用/ post /:id
meaning a URL will look like /post/post-title instead of /post/1 表示网址看起来像/ post / post-title而不是/ post / 1
I have the controller framed properly with this code. 我已使用此代码正确构造了控制器。
def show
@post = Post.find(params[:friendly])
respond_to do |format|
format.html
format.json { render :json => @post }
end
end
But I am not sure how to change routes.rb to implement this change. 但是我不确定如何更改route.rb以实现此更改。
Right now it just says 现在它只是说
resources :post
Thanks in advance for your help. 在此先感谢您的帮助。
You can use to_param method on the model http://apidock.com/rails/ActiveRecord/Base/to_param 您可以在模型http://apidock.com/rails/ActiveRecord/Base/to_param上使用to_param方法
If you keep object ID inside of the friendly, ex 1-some-name, 2-some-other-name you will not have to do anything else. 如果将对象ID保留在友好的(例如1-some-name,2-some-other-name)内,则无需执行其他任何操作。 Rails will strip id from the string and will use it to find your object.
Rails将从字符串中删除ID,并将其用于查找对象。 If you don't, you will have to change your controllers to use find_by_friendly(params[:id]) instead of find(params[:id])
如果不这样做,则必须更改控制器以使用find_by_friendly(params [:id])而不是find(params [:id])
Another alternative is to use a gem like https://github.com/norman/friendly_id to accomplish this. 另一种选择是使用https://github.com/norman/friendly_id之类的gem来完成此任务。
If you want to change the format of the id variable on find, you can change the route as follows 如果要在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
then, to get the post in posts#find, you need to do 然后,要获取帖子中的帖子#find,您需要
Post.find_by_friendly(Params[:id])
One problem is that this will break the helper paths - eg post_path(@post)
will need to become post_path(:id => @post.friendly)
一个问题是,这将破坏助手路径-例如
post_path(@post)
将需要成为post_path(:id => @post.friendly)
http://guides.rubyonrails.org/routing.html#http-verb-constraints http://guides.rubyonrails.org/routing.html#http-verb-constraints
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.