开发者

Rails security validations in controller?

开发者 https://www.devze.com 2023-03-21 09:11 出处:网络
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])

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
0

精彩评论

暂无评论...
验证码 换一张
取 消