Rails security validations in controller?
I'm wondering if there is a best way to achieve this the rail way in my controller :
def show
@article = Article.find(params[:id])
# you can only view a public article or your own articles.
@article = nil unless @article.public? || @article.owner?(current_user)
e开发者_开发百科nd
def edit
@article = Article.find(params[:id])
# you can only edit your own articles
@article = nil unless @article.owner?(current_user)
end
I have a couple validations like this in my application and I can clearly see it's easy to miss one and give access to something that you should not!
Thanks
it is not the Rails way. one of the rails principles is take all the object manipulation on Model layer. Controllers mostly cares about overall authorizations/authentication/cache invalidation/cookie and sessions settings.
you can use associations and scope
class ArticlesControllers << ApplicationsController
def show
@article = current_user.articles.public.find(params[:id])
end
end
class Article < ActiveRecord::Base
scope :public, :where('public').is('true')
end
Honestly, I'd use CanCan.
can :read, Article, public: true
can :manage, Article, owner_id: user.id
精彩评论