rails 根据activerecord动态创建路由

使用ActionDispatch::Routing::PolymorphicRoutes中提供的方法根据AR动态创建路由,以下为官方文档:

Polymorphic URL helpers are methods for smart resolution to a named route call when given an Active Record model instance. They are to be used in combination with ActionController::Resources.

These methods are useful when you want to generate the correct URL or path to a RESTful resource without having to know the exact type of the record in question.


以上的前提:

  1. RESTful resource

提供的方法

  1. polymorphic_url/polymorphic_path
  2. edit_polymorphic_url/edit_polymorphic_path
  3. new_polymorphic_url/new_polymorphic_url

例子

1. polymorphic_path User => /users
2. polymorphic_path @user => /users/1
3. new_polymorphic_path User => /users/new
3. edit_polymorphic_path User => /users/1/edit