繁体   English   中英

Ruby on Rails中的自定义URL路由

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM