user2012677
user2012677

Reputation: 5745

Singular Model,Controller, Form_for reference

I have a singular model, controller, view named "product". In my routes, I used activemodel so there is no pluralization.

Routes:

resource :product, :controller => 'product'

When I use form_for:

<%= form_for( @product) do |f| %> 

But I get the following error:

undefined method `products_path'

How do I fix this? It should be product_path.

Upvotes: 3

Views: 92

Answers (3)

Sylvain FARNAULT
Sylvain FARNAULT

Reputation: 112

When you write:

#config/routes.rb    
resources :product, :controller => 'product'

For create action it generates alias product_index for "/product" path

But form_for don't know that and, by convention, will look for products_path, producing your error.

I think it's best to adapt routes to keep form_for to be abble to work on his own (for new/create and edit/update)

We assume that you have your singular controller, it could be to much pain to change that in your app, so we stay with it.

What you can do in your routes

#config/routes.rb
resources :product, only: [:index, :create], as: :products
resources :product, except: [:index, :create]

For create action, that will produce:

POST "/product" => "product#create", as: "products"

And form_for will be happy

Upvotes: 0

Richard Peck
Richard Peck

Reputation: 76784

A better way is to use the plural for your controller name (as per convention), and singular for the route:

#config/routes.rb
resource :products, controller: "product", path: "product" #-> url.com/product/:id

Upvotes: 0

user2012677
user2012677

Reputation: 5745

I just found the solution. There are two methods to do this.

1) Add this to the Model file. model_name.instance_variable_set(:@route_key, 'product')

OR

2) = form_for @product, :url => product_path do |f|

Upvotes: 1

Related Questions