Reputation: 17981
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_path
s.
Is it possible to have all the Rails convention goodies while my model and controller have different names?
Upvotes: 5
Views: 8169
Reputation: 41
So I've got a custom C.R.M. that I've built, and it uses employees_controller to pass and retrieve values from Devise's User model. I didn't want Devise views to be accessible, but I wanted to use Devise for user authentication since... let's face it, they've got that figured out pretty darn well.
Well, as it turns out, I was having some trouble with this same issue, I had an embedded Ruby tag for the form:
<%= form_for @employee, as: :user, url: employees_path do |f| %>
The problem here should be obvious (though it took me a good hour to find) - if I'm on the "new" action, it'll work great. It'll take the form data, pass that into a new User.new object, and create a new user for me. But, if I'm trying to edit my employee's information, say by updating their password or by adding some more to their description, it'll fail - saying there is no "[PATCH] method for path /employees", which is true.
A little hacky I suppose, but my solution was simply to put an @path instance variable in the "new" and "edit" actions:
def new
@path = employees_path
end
def edit
@path = employee_path
end
I tested it, and it works great. If anyone has any critique to this method, by all means - I'd love to hear it.
My environment:
Upvotes: 1
Reputation: 2015
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
Upvotes: 12
Reputation: 5302
you can add a option: url: employee_path
e.g.
<%= form_for @people, :as => :post, :url => employee_path(@people) do |f| %>
...
<% end %>
Upvotes: 6