Reputation: 3654
Banging my head against a wall and staring at my code, insisting that it's right isn't working.
I have a simple blogging Rails 4 app that creates, reads, and updates posts just fine. But I need to put the "D" in CRUD.
My posts_controller has these methods:
def create
@post = current_user.posts.build(post_params)
if @post.save
redirect_to @post, notice: 'Post was successfully created. Huzzah!'
else
render action: 'new'
end
end
def edit
@post = Post.find(params[:id])
if current_user
redirect_to root_path, notice: 'Not permitted :(' unless current_user.id.to_i == @post.user_id.to_i
else
redirect_to root_path, notice: 'Not permitted :('
end
end
def destroy
@post.destroy
redirect_to root_path, notice: 'Post was successfully destroyed. Sad face.'
end
def update
@post = Post.find(params[:id])
if @post.update(post_params)
redirect_to @post, notice: 'Post was successfully updated. Hooray!'
else
render action: 'edit'
end
end
and my (slim) form looks has this:
= link_to 'Cancel', posts_path
= link_to 'Delete', @post, method: :destroy, data: { confirm: 'Are you sure?' }
When I edit the post in the app, I get redirected back to to post.
Upvotes: 0
Views: 111
Reputation: 4966
There are a couple of things wrong with your code.
First, you need to set the @post
variable in your destroy
method:
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to root_path, notice: 'Post was successfully destroyed. Sad face.'
end
The method
param on your link_to
is also incorrect. It should be delete
, not destroy
:
= link_to 'Delete', @post, method: :delete, data: { confirm: 'Are you sure?' }
(Destroy is the name of the controller method, but delete is the name of the HTTP verb that is used to route to it)
Upvotes: 3