ruby-on-rails-3 - 在 route 将:id定义为不同于Rails 3中的id

标签 ruby-on-rails-3 routes

我正在将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/

相关文章:

ruby-on-rails - 如何在数据库中反射(reflect) Ruby on Rails 中新的 belongs_to 和 has_many 关系

ruby-on-rails-3 - 是否可以使用事件管理呈现普通模板 html.erb 模板?

ruby-on-rails-3 - 轨道 3 中的观察字段

ruby-on-rails - 定义一个方法来捕获类中的a_method[]

ruby-on-rails - 无法安装 sqlite3 并运行捆绑安装

javascript - Sammy.js 路由 : How to wait for a library to be loaded before routing

php - 西莱克斯 2 : RegEx in routing

javascript - 如何使用 NodeJS 构建单页、使用 API 的应用程序

solr - SolrCloud 上的自定义分片或自动分片?

Angular2 获取事件路线