Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form_for with model name different to controller

I have a model called Person, and I want to have a resource called Employee. I found that this will stop the form_for magic.

I need to pass in the @person object itself so form_for can choose the correct action path (create or update).

However this will mean that form_for uses POST people_path and PUT person_path in the output, instead of employee_paths.

Is it possible to have all the Rails convention goodies while my model and controller have different names?

like image 721
lulalala Avatar asked Dec 02 '22 19:12

lulalala


2 Answers

If you want to use "employees" in routes/url you can use "path" in routes eg. create controller as people_controller but in routes

resources :people, path: "employees"

so routes will be like

new_person GET    /employees/new
people GET    /employees

etc

So following will work

<%= form_for @people do |f| %>
  ...
<% end %>

Note: For this You have to use Person model

like image 160
jbmyid Avatar answered Dec 22 '22 17:12

jbmyid


you can add a option: url: employee_path

e.g.

<%= form_for @people, :as => :post, :url => employee_path(@people) do |f| %>
  ...
<% end %>
like image 40
lfx_cool Avatar answered Dec 22 '22 18:12

lfx_cool