I’ve got a view for entering / editing posts.
I want to stop people from creating or editing posts if they are not logged in (in the model) & I want to redirect the ./posts/new view to the posts list with a “You cannot create new posts if you’re not logged in” message.
I’ve tried changing the “new” command in the posts controller as so:
def new
if !session[:user]
redirect_to(@posts, :notice => 'You cannot create a post unless you are logged in.')
return
end
@post = Post.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @post }
end
end
but that doesn’t work.
I don’t know if I should put the logic for what I want to do in the controller, in the view or in the model. (Or some combination of all 3).
I’m guessing that I should only be putting it in one place (DRY, etc), but I don’t know where.
Try using a
before_filter :verify_authenticated. Check out the documentation on the API: http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html. The second example is exactly what you’re looking for. You authentication check can go into your ApplicationController so you’ve got it in one place.Or check out “prettier” notes from the guide: http://guides.rubyonrails.org/action_controller_overview.html#after-filters-and-around-filters