1

我想知道注册后立即登录用户的好方法是什么。我不需要电子邮件确认,因此用户没有理由不期望这会自动发生。

  def create
    @user = User.new(params[:user])

    respond_to do |format|
      if @user.save
        format.html { redirect_to welcome_url, notice: "Your user: #{@user.name} was successfully created! Please log in!" }
        format.json { render json: @user, status: :created, location: @user }
      else
        format.html { render action: "new" }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

我看到的一个问题是我没有直接连接到 POST session#create 的路由。看起来我应该,但没有具体的路线

controller :sessions do
   get    'login'  => :new
   post   'login'  => :create
   delete 'logout' => :destroy
   get 'logout' => :destroy
end

产量:

login GET    /login(.:format)                        sessions#new
      POST   /login(.:format)                        sessions#create
logout DELETE /logout(.:format)                       sessions#destroy
       GET    /logout(.:format)                       sessions#destroy

供参考,这是我的会话#create 方法

def create
  user = User.find_by_name(params[:name])
  if user and user.authenticate(params[:password])
    session[:user_id] = user.id

    if session[:return_to]
      redirect_to session[:return_to]
      session[:return_to] = nil
      return
    end
    redirect_to eval("#{user.role}_url")

  else
    redirect_to login_url, alert: "Invalid user/password combination"
  end
end

我可以直接从我的 user@create 控制器方法挂钩到我的 session#create 路由,就好像用户除了第一次登录一样吗?

4

1 回答 1

1

You cannot redirect with post method. See redirect_to using POST in rails. So your options are: 1. Access the sessions model and create a record there from the users create method, or 2. (Not recommended) Create a GET access to the sessions#login method. I hope this helps.

于 2012-05-30T03:38:20.660 回答