Ruby on Rails中的自定义URL路由

时间:2012-09-17 23:38:21

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1

我目前正在使用3.0

在rails上学习ruby

我创建了一个名为friendly

的列的帖子表

而不是使用/ post /:id我想使用/ post /:friendly

表示URL看起来像/ 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

但我不知道如何更改routes.rb来实现此更改。

现在它只是说

resources :post

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

您可以在模型http://apidock.com/rails/ActiveRecord/Base/to_param

上使用to_param方法

如果您将对象ID保留在友好的ex 1-some-name,2-some-other-name中,您将不必执行任何其他操作。 Rails将从字符串中删除id并将使用它来查找您的对象。如果不这样做,则必须更改控制器以使用find_by_friendly(params [:id])而不是find(params [:id])

另一种选择是使用类似https://github.com/norman/friendly_id的宝石来实现这一目标。

答案 1 :(得分:0)

如果要在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