问题
in a Rubyonrails application i want only logged in users to enterinto the inner pages? how can i redirect the direct entered urls to index page?
in php if(!isset($_SESSION[id]) { header("location:index.php") }, how this can be implemented in ruby on rails
回答1:
here goes
In application_controller.rb:
Putting this code in application_controller will make it available to all your controllers.
class ApplicationController < ActionController::Base
protect_from_forgery
protected
def confirm_logged_in
unless session[:id]
flash[:notice] = "Please log in"
redirect_to :root
return false
else
return true
end
end
end
Then you can make use of this method in any of the controllers that require it, for eg
If you need to confirm that users are logged in for the show action, then
class UsersController < ApplicationController
before_filter :confirm_logged_in, :only => [:show]
def show
#all your code
end
end
should work, as this will confirm that users accessing this show url have logged in.
For more info checkout this link to rails guides on filters. There could be more efficient ways of achieving this as well.
However, i would suggest using a gem like Cancan (Github) as i have used this in many apps and works well. The code presented above is basic and there are many better and advanced ways to handle this but it should do the job.Hope it helps.
来源:https://stackoverflow.com/questions/8500350/how-to-allow-access-only-to-logged-in-users-restricting-direct-entry-of-url