Haven't needed to use the rails 'url helpers' before, but I am trying to implement something like Rails: URL/path with parameters . I did not create any 'resources', but I was under the impression I could prepend the url_helper name in the routes like:
user_index_path GET 'users/index', to: 'users#index'
but this gives the error:
undefined method 'GET' for #<ActionDispatch::Routing::Mapper:0x00000007ABCDEF> Did you mean? gets gem
Since I haven't used them much, I'm also confused by the statement I read here, https://blog.arkency.com/all-the-ways-to-generate-routing-paths-in-rails/ , saying "Of course instead of _path sometimes you are going to need _url". Am I defining them wrong? Yes, I read https://guides.rubyonrails.org/routing.html , and saw the bit about '3.16 Direct routes', but this doesn't jive with the examples I've 'seen'.
You can name routes whatever you want
#inside your routes.rb file
get 'users/index', to: 'users#index', as: 'users_index'
(note the "get" undercase, what you see on the first link is the output of the command rake routes
, not the line when you define them)
That route will give you 2 named routes to use: users_index_path
and users_index_url
(the latter includes protocol, host, and port).
I must admit the official Rails routing documentation is quite terse. In short, you can't prepend the path in your routes.rb file. Your line should instead read as follows:
get 'users/index', to: 'users#index'
If you now visit http://localhost:3000/rails/info/routes or type rails routes in your project folder's command prompt, you will see that this gives you the users_index_path helper (note the plural). If you wanted this to be the singular - as in your original question - add the "as" option:
get 'users/index', to: 'users#index', as: 'user_index'
Then you can use user_index_path in your view templates.
You're defining the routes wrong.
Try something like this:
get 'users/index' => "users#index", as: :users
Then you will get a helper like this: users_path
Are you confusing controller actions with routes? Nobody defines a route as 'index'. That's simply assumed.
What you really want will be something like this:
resources :users, :controller => "users", :only => [:index]
Then you can use users_path
to get to a collection of users.
What it does:
:only => [etc]
bit. I believe the simplest and most conventional thing to do would be:
get :users, to: 'users#index'
which gives you:
users GET /users(.:format) users#index
which you would then use as users_path
.
If you want to go down the resources
path (so to speak), then:
resources :users, only: [:index]
Which also gives you:
users GET /users(.:format) users#index
It is unconventional to have user_index_path
since users_path
implies by convention the index action for the UsersController
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.