ruby-on-rails - 用户注册后如何立即登录?

标签 ruby-on-rails ruby ruby-on-rails-3 authentication registration

我知道我应该将代码放入用户 Controller 的创建操作中,但我不确定应该放入什么代码。我还假设它应该在我的 session Controller 中调用创建操作,但我再次不确定如何...

顺便说一句,我在用户 Controller 的创建操作中尝试了render :template => 'sessions/create',但在注册时出现此错误:

Template is missing

Missing template sessions/create with {:locale=>[:en, :en], :formats=>[:html], :handlers=>[:rjs, :rhtml, :erb, :rxml, :builder]} in view paths "/rubyprograms/dreamstill/app/views", "/rubyprograms/dreamstill/vendor/plugins/facebox_render/app/views"

这一切都在我的应用程序 Controller 中:

protected 
  # Returns the currently logged in user or nil if there isn't one
  def current_user
    return unless session[:user_id]
    @current_user ||= User.find_by_id(session[:user_id]) 
  end


  # Make current_user available in templates as a helper
  helper_method :current_user

  # Filter method to enforce a login requirement
  # Apply as a before_filter on any controller you want to protect
  def authenticate
    logged_in? ? true : access_denied
  end

  # Predicate method to test for a logged in user    
  def logged_in?
    current_user.is_a? User
  end

  # Make logged_in? available in templates as a helper
  helper_method :logged_in?

  def access_denied
    respond_to do |format|
      format.html do
        flash[:alert] = "You must log in to peform this action."
        redirect_to root_path
      end

      format.js do
        render_to_facebox(:partial => 'sessions/login_box')
      end
    end
     false
  end

最佳答案

在你的 Controller 中的某个地方,你有一些看起来像这样的东西:

user = User.new
# set attributes
user.save
render :template => 'sessions/create' # Probably based on your question

您所需要做的就是将 session 更新为:

user = User.new
# set attributes
if(user.save)
   session[:user_id] = user.id
   # Send them somewhere useful
else
   # Handle the error
end

设置session[:user_id]后,他们就会登录。

关于ruby-on-rails - 用户注册后如何立即登录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5438606/

相关文章:

ruby-on-rails - 有没有 "Ruby on Rails gem"这样的东西?

javascript - 日期时间选择器的默认设置今天日期

ruby-on-rails - 设置多态关联

ruby - 给定散列中的多个其他值,如何在散列数组中查找并返回散列值

ruby-on-rails - Rails 3 中的 config.logger 和 config.paths.log

ruby-on-rails - 用于新闻解析片段的 ruby​​ gem

ruby-on-rails - heroku I18n 语言环境不同于 default_locale,在本地工作正常

ruby-on-rails - 使用强参数 Rails 创建和更新嵌套模型

ruby-on-rails - 如何在 ruby​​ 的 http 请求中包含 header

ruby-on-rails - 将 "complex"JSON 数据转换为散列