我正在将Merb应用移植到Rails3。在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相同的东西。我想念吗?
我可以重构事物,也许在这种情况下可能不需要它,但是我仍然想知道我是否错过了什么。
谢谢。
最佳答案
我遇到了同样的问题;事实证明,最好的方法是在调用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。如果您将字符串传递给它,它将只解析该字符串。
关于ruby-on-rails-3 - 在 route 将:id定义为不同于Rails 3中的id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3818268/