Routes: resources, using a member or collection for a custom action?

Hello everyone, I am making an application with rails 3.2. I am trying to use form_tag , but I have a problem with the route.

I try this in my form:

 = form_tag('/companies/save_category', method: "post") do 

and this:

 = form_tag({:controller => "companies", :action=>"save_category"}, method: "post") do 

In my config/routes.rb :

I'm a little confused to get a route like this

 resources :companies do post 'save_category' end 

or follow these routes:

 resources :companies do member do post 'save_category' end end 

But in any case, this will not work. And when I do rake routes , I get the same result

 company_save_category POST /companies/:company_id/save_category(.:format) companies#save_category 

The error was this

 No route matches [POST] "/companies/save_category" 

any idea?

+4
source share
1 answer

Consider these routes:

 resources :companies do member do post 'save_category' end end 

This member block means that the save_category route in the /compagnies/ namespace requires a company identifier to work:

 /compagnies/12/save_category # where 12 is params[:company_id] 

Now, with the collection:

 resources :companies do collection do post 'save_category' end end 

This means that to go to the save_category route, you do not need a company identifier:

 /compagnies/save_category # will work, is not needing a params[:company_id] 

In your case , you should first use the URL helpers (generated after route.rb). You need here:

 if save_category is a *member route* save_category_company_path(@company) elsif save_category is a *collection route* save_category_companies_path 

I think the category you want to keep is related to a specific company, right? If so, do you need a member route:

 form_tag(save_category_company_path(@company), method: "post") do 

Hope this helps!

+3
source

Source: https://habr.com/ru/post/1501684/


All Articles