想象一下,我们有一个Article
和一个Comment
模型。我们设置了以下路线:
# routes.rb
resources :articles do
resources :comments
end
现在,我们可以通过comment
销毁CommentController
,但我看到有很多方法已经实施。
# method 1
def destroy
Comment.where(article_id: params[:article_id]).find(params[:id]).destroy
end
# method 2
def destroy
Comment.find(params[:id]).destroy
end
# method 3
def destroy
article = Article.find(params[:article_id])
comment = article.comments.find(params[:id])
comment.destroy
end
哪个更好,为什么?
我在旧的Railscasts剧集和博客中看到我们应该出于“安全”原因而做前者,或者因为最好确保comments
只能在各自的article
内找到{{1}} 1}},但为什么那更好?我找不到任何过于深入答案的内容。
答案 0 :(得分:1)
当您以这种方式处理嵌套数据时,最好将模型查找范围限定在父级下,以避免人们以简单的方式迭代id。你通常想要阻止它,如果这是一种习惯,它会保护你免受更严重的安全问题。
例如,假设您对Article有某种可见性权限。使用方法2,可以使用允许您查看的article_id
来访问您不是的注释。
方法1& 3表面上做同样的事情,但我更喜欢1,因为它使用较少的DB访问。