之前不需要使用rails'url helpers',但我正在尝试实现类似Rails: URL/path with parameters的东西。我没有创建任何“资源”,但我的印象是我可以在路由中添加url_helper名称,例如:
user_index_path GET 'users/index', to: 'users#index'
但是这给出了错误:
undefined method 'GET' for #<ActionDispatch::Routing::Mapper:0x00000007ABCDEF> Did you mean? gets gem
由于我没有太多使用它,我也对我在这里读到的声明https://blog.arkency.com/all-the-ways-to-generate-routing-paths-in-rails/感到困惑,说“当然有时你需要_url而不是_path”。我定义错了吗?是的,我读了https://guides.rubyonrails.org/routing.html,并看到了关于'3.16直接路线'的一点,但这与我见过的例子没有关系。
您可以根据需要为路线命名
#inside your routes.rb file
get 'users/index', to: 'users#index', as: 'users_index'
(注意“获取”大写,你在第一个链接上看到的是命令rake routes
的输出,而不是定义它们时的行)
该路由将为您提供2条命名路由:users_index_path
和users_index_url
(后者包括协议,主机和端口)。
我必须承认官方Rails路由文档非常简洁。简而言之,您不能在routes.rb文件中添加路径。您的行应改为:
get 'users/index', to: 'users#index'
如果您现在访问http://localhost:3000/rails/info/routes或在项目文件夹的命令提示符下键入rails routes,您将看到这为您提供了users_index_path帮助程序(请注意复数形式)。如果您希望这是单数 - 如在原始问题中 - 添加“as”选项:
get 'users/index', to: 'users#index', as: 'user_index'
然后,您可以在视图模板中使用user_index_path。
你定义错误的路线。
尝试这样的事情:
get 'users/index' => "users#index", as: :users
然后你会得到一个这样的帮手:users_path
您是否将控制器操作与路线混淆?没有人将路线定义为“索引”。这是简单的假设。
你真正想要的是这样的:
resources :users, :controller => "users", :only => [:index]
然后你可以使用users_path
来访问一组用户。
它能做什么:
:only => [etc]
位。我认为最简单和最传统的做法是:
get :users, to: 'users#index'
这给你:
users GET /users(.:format) users#index
然后你将用作users_path
。
如果你想沿着resources
路走下去(可以这么说),那么:
resources :users, only: [:index]
这也给你:
users GET /users(.:format) users#index
由于user_index_path
按照惯例暗示users_path
的指数行动,因此拥有UsersController
是非常规的。