我的头靠在墙上,盯着我的代码,坚持说它是对的不行。
我有一个简单的博客Rails 4应用程序,可以很好地创建,阅读和更新帖子。但我需要把" D"在CRUD。
我的posts_controller有以下方法:
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
我的(苗条)形式看起来有这个:
= link_to 'Cancel', posts_path
= link_to 'Delete', @post, method: :destroy, data: { confirm: 'Are you sure?' }
当我在应用中编辑帖子时,我会被重定向回发布。
答案 0 :(得分:3)
您的代码存在一些问题。
首先,您需要在@post
方法中设置destroy
变量:
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to root_path, notice: 'Post was successfully destroyed. Sad face.'
end
method
上的link_to
参数也不正确。它应该是delete
,而不是destroy
:
= link_to 'Delete', @post, method: :delete, data: { confirm: 'Are you sure?' }
(Destroy是控制器方法的名称,但delete是用于路由到它的HTTP谓词的名称)