开发者

How do I protect a specific page from being viewing with out login in ruby on rails

I want to protect a specific page in a controller from access only if the user is logged in it is the add.html page for adding questions, the index.html page is used to show questions that are asked but I want to to remain public. How do I make it that when someone clicks on ask a question from index that it checks for login and if开发者_如何学C not logged in has flash notice saying you must login and redirect at same time to login page.

New error on index page:

NoMethodError in Car#index

Showing app/views/car/index.html.erb where line #3 raised:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each
Extracted source (around line #3):

1: <h2>Current List of Open Questions</h2>
2: <dl>
3: <% @car.each do |car| %>
4:   <dd>
5:     <%= car.name %><br />
6:     <%= car.description %><br />


If you're using a login system already, you could set a before filter to only authenticate on the actions your desire.

before_filter :authenticate, :except => :index


You want to add a before_filter to ensure the user is logged in before running the protected actions. Here's a simple example - naturally your implementation details depend on how you rolled your own auth.

In your application controller (assuming you're storing the id of the current logged in user in session[:user_id]):

class ApplicationController < ActionController::Base
  protected
  def ensure_login
    if session[:user_id].blank?
      flash[:notice] = 'You must be logged in to use this part of the site.'
      begin
        redirect_to :back
      rescue
        redirect_to '/'
      end
      return false
    end
  end
end

and then in the controller where you are limiting access:

class QuestionsController < ApplicationController
  before_filter :ensure_login, :only => [ :add ]
end


Instead of writing the login code yourself, you should look into gems like Devise, Authlogic and Restful authentication - (listed in decreasing order of stuff you have to do to get things up and running)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜