Reputation: 694
I'm doing 2 forms, 1 for create and 1 for edit. The create form works great. The edit form generates this error
No route matches [PATCH] "/admin/posts/14/edit"
In the form, I guess the problem is "patch". I changed that for "edit" and url admin_posts_path, like the "create" form, but this produces a new item, not edit the current one. This is my rake routes on this part
admin_posts GET /admin/posts(.:format) admin/posts#index
POST /admin/posts(.:format) admin/posts#create
new_admin_post GET /admin/posts/new(.:format) admin/posts#new
edit_admin_post GET /admin/posts/:id/edit(.:format) admin/posts#edit
admin_post GET /admin/posts/:id(.:format) admin/posts#show
PUT /admin/posts/:id(.:format) admin/posts#update
DELETE /admin/posts/:id(.:format)
And this is the form or at least the important part
<%= form_for :post, url: edit_admin_post_path(@post),:html => { :multipart => true }, method: :patch do |f| %>
Upvotes: 1
Views: 156
Reputation: 7543
If your create
action is working then you don't need to pass url
for edit. Rails can determine which path to choose by calling new_record?
method. If object is new_record
than rails will use admin/posts#create
method but if you object is not new_record
than rails will use admin/posts#update
method. So your controller will look like this
class Admin::PostsController < ApplicationController
def new
@post = Post.new
end
def create
//some code
end
def edit
@post = Post.find(params[:id])
end
def update
//some code
end
end
and than you can create form
like this
form_for @post do |f|
//code here
end
now rails can automatically determine which path to use for new
post and editing
post
Upvotes: 1
Reputation: 697
edit_admin_post
only for GET http verb.
Your form should reference to PUT /admin/posts/:id
to update your post.
change your form to:
<%= form_for @post, { multipart: true } do |f| %>
<% end %>
Upvotes: 1
Reputation: 18702
The edit
action only responds to GET requests. The actual update is done in the update
action, which responds to PUT (or PATCH if you use Rails 4).
Your edit form should start with this:
<%= form_for :post, url: admin_post_path(@post),:html => { :multipart => true }, method: :put do |f| %>
You could also simplify this to:
<%= form_for @post, html: { multipart: true } do |f| %>
This will automatically set the form action to PUT admin/posts/:id
for existing records, and POST admin/posts
for new records.
Upvotes: 1