Rails – How to Solving “undefined method …_index_path”
Rails provide us a feature to generate CRUD code for a table. It will generate models, controller event views which is needed by application. Well it’s very help but “generates” thing not always understand with ours and sometime it result error and one of error that often happen here is “undefined method …_index_path” error.
WHERE IT HAPPEN?
It often come from the views “_form.html.erb” file on this code:
<%= form_for @data do |f| %>
WHY IT HAPPEN?
It come because rails cant recognize the path that will run when form is submitted. This happen sometime because developer using not recommended name for model on rails.
<%= form_for @data do |f| %>
this code will run a url from variabel @data when we do submit, @data come from controller value:
# data from action new def new @data=YourModel.new end # data from action edit def edit @data=YourModel.find(params[:id]) end
Rails automatically generate an url when you use that value on you form_for tag with this condition:
- By default it will generate url yourmodels_path (using your model name with suffix “s” and join it with “_path” from the “new” model, for example Car.new will return “cars_path” for the url.
- In some conditions it will generate “yourmodel_index_path”, for example Cars.new will generate “cars_index_path”. What condition that can make this difference? well i dont know the detail list, but this is some of them:
- when your model name end with “s” character: Cars, Mans, Toys, etc
- when you model name end with “ta”: Sista, etc..
HOW TO FIX IT?
If you can change your model name with the good one, just change it. It will save your time. But if you need to keep your models name, you can manually change your form_for tag url like this:
<%= form_for @data, :url => enter_your_path_here do |f| %>
If you using rails generate feature it will use file “form.html.erb” on the view twice, from “new.html.erb” and “edit.html.erb. which is use when you insert new data and update existing data. Since it call twice and will call different path for submit event, you can insert this code on your “new.html.erb” file:
<%= render 'form', url: models_path %>
and insert this code on your “edit.html.erb” file:
<%= render 'form', url: model_path %> # their different is "s" on the end of model name
make sure new and edit file have same name for url variable so you can consume them on the form.html.erb like this:
<%= form_for @data, :url => url do |f| %>
And it will fix your error..
Finish.. hope it help..
Happy coding!