我正在将一个Merb应用程序移植到Rails 3.在Merb中,我们可以在路径周围放置一个Identify块来定义如何提供:id路由参数,例如,
# this is a Merb route that I want to port to Rails 3 routing; I get everything except
# how to replicate the behavior of Merb's Identify block which doesn't require one to
# futz with overriding to_param on user; a user instance gets passed to the url builder
# ala url(:edit_password_reset, user) and this tells the router to use the
# reset_password_token method on user to supply the :id value for this one route
Identify User => :reset_password_token do
match("/reset-password/:id", :method => :get).to(:controller => "password_resets", :action => "edit").name(:edit_password_reset)
end
# and then later define more routes that use the user's id without a problem
# since to_param was not overridden on user; here I have already translated to
# Rails 3 and this works fine
controller :users do
get "/register", :action => "new", :as => "new_user"
get "/users", :action => "index", :as => "users"
get "/users/:id", :action => "show", :as => "show_user"
get "/users/:id/edit", :action => "edit", :as => "edit_user"
put "/users/:id", :action => "update", :as => "update_user"
post "/users", :action => "create", :as => "create_user"
end
在Rails中,与Merb一样,您可以覆盖to_param以为路由提供替代id值,但是对于一次要使用id而另一次要在同一对象上使用不同方法的情况(如上所述),识别很方便。什么是Rails 3等价物?我查看了Rails 3源代码并进行了测试,没有发现任何与Identify相同的内容。我错过了吗?
我可以重构一些事情,也许在这种情况下不需要它,但我仍然想知道我是否错过了什么。
感谢。
答案 0 :(得分:1)
我遇到了同样的问题;事实证明,最好的方法是在调用url或路径时完全跳过to_param。例如:
# This will set params[:id] to @user.to_param
edit_password_reset_url(@user)
# This will set params[:id] to @user.reset_password_token
edit_password_reset_url(@user.reset_password_token)
换句话说,只有在将记录传递给url助手时才会调用to_param;如果你传递一个字符串,它只会解析字符串。