Rails:修改to_param后手动定义路由

时间:2013-06-08 15:01:41

标签: ruby-on-rails

我一直在努力为用户个人资料实现一个虚荣网址,基于此处的示例:Rails 3: Permalink public profile。我用'username'替换了'id':

  def to_param
    username
  end

然而,这导致我的其他路线出现问题。我设置了它们,以便在运行“rake routes”时完全匹配默认的路由集。

  get '/users/' => 'users#index', :as => :users
  post '/users' => 'users#create'
  get '/users/new' => 'users#new', :as => :new_user
  get '/users/:id/edit' => 'users#edit', :as => :edit_user
  patch '/users/:id' => 'users#update'
  put '/users/:id' => 'users#update'
  delete '/users/:id' => 'users#destroy'

  # for vanity url
  get '/:id' => 'users#show', :as => :user

通过此设置,尝试访问删除和更新路由会给我“无路由匹配”错误。指定这些的正确方法是什么,和/或我应该以不同的方式做到这一点?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

我认为将resources语法保留在routes.rb中除了show,您可以重写以自定义user_path之外,保持resources :users, :except => [:show] # 2 possibilities for the show url get '/users/:id' => 'users#show' # can be removed if you don't want to keep /users/:id url get '/:id' => 'users#show', :as => :user 语法的有趣性和可读性:

username

但是更改控制器以按id而不是def show @post = Post.find_by_username(params[:id]) # instead of Post.find(params[:id]) # ... end 查找用户,例如

{{1}}