Authentication with 'before_filter'
I'm trying to figure out before_filters
and I was hoping for a little help.
I have a simple blog app, with entries that can be (draft or published) and (public or private). I was 开发者_C百科wondering how I can do my authentication?
I currently have:
before_filter :authenticate, :except => [ :show ]
So that blocks all the CRUD actions. For show
, I need to check that:
- If its a draft, that the logged in user owns the entry.
- If its private, a user is logged in (in this, all logged in users can see private entries)
I can do it within the action itself, but it seems that the rails way of doing it, is in a before_filter
.
Thanks!
Do it in the before filter. If you are using devise then the current_user method is available if a user is logged in. Otherwise replace current_user with the value returned from your authenticate method.
def find_post
@post = Post.find(params[:id])
redirect_to root_path if @post.draft && @post.user != current_user
redirect_to root_path if @post.private && !current_user
end
精彩评论