我正在用RoR编写一个应用程序,我想知道是否应该将if语句放在那里:
class ArticlesController < ApplicationController
before_action :set_user, only: %i[destroy edit]
...
def destroy
if @article.destroy
flash[:success] = 'Article deleted'
redirect_to articles_path
else
flash[:error] = 'Failed to delete the article'
redirect_to article_path(@article)
end
end
...
private
def set_user
@article = Article.find(params[:id])
if current_user.id == @article.author_id
@author = current_user
else
redirect_to article_path(@article), message: 'You can\'t do that'
end
end
end
是否可以调用“else”分支i destroy方法?我正在为该控制器编写规范,我不可能想到测试该代码的方法。 我使用与“.save”相同的方法,但我们正在处理数据库验证。如果无法调用“else”,我将删除这些行。
我在搜索文章所有者或通过id查找文章时出现问题,错误将在“set_user”方法中提前出现。