轨道3中的助手是否可使用表格的参数?

时间:2011-10-03 17:23:43

标签: ruby-on-rails ruby ruby-on-rails-3 rubygems ruby-on-rails-3.1

我正在关注迈克尔哈特的教程,用登录建立一个注册表单。我想我会尝试在登录表单中添加一个记住我的复选框,并将其默认值设置为0,然后选中1。

我在sessionshelper中添加了一个if语句:

module SessionsHelper

  def login(user)
    if params[:remember_me]
    cookies.permanent.signed[:remember_token] = [user.id, user.password_salt]
    current_user = user
   else
    cookies[:remember_token] = [user.id, user.password_salt]
    current_user = user
   end
  end

  def current_user=(user)
    @current_user = user
  end

  def current_user
    @current_user ||= user_from_remember_token
  end

  def logged_in?
    !current_user.nil?
  end

  def logout
    cookies.delete(:remember_token)
    current_user = nil
  end

  private

  def user_from_remember_token
    User.authenticate_with_salt(*remember_token)
  end

  def remember_token
    cookies.signed[:remember_token] || [nil, nil]
  end

end

....但出于某种原因,当我登录盒装托运或未检查时,从未设置过期时间和日期。当我在firefox中检查cookie信息时,它总是说“在会话结束时”。我错过了什么吗?

我的控制员:

class SessionsController < ApplicationController

  def new

  end


  def create
    user = User.authenticate(params[:session][:email], params[:session][:password])
    if user.nil?
      flash.now[:error] = "Invalid email password combination"
      render 'new'
    else
      login user
      redirect_to user
    end
  end

  def destroy
    logout
    redirect_to root_path
  end
end

视图:

<%= form_for(:session, :url => sessions_path) do |f| %>
  <%= f.text_field :email, :placeholder => "Email" %>      
  <%= f.password_field :password, :placeholder => "Password" %>     
  Remember me? <%= f.check_box :remember_me, :value => 1 %>
  <%= f.submit "Log in", :id => "login_submit" %>
  <% end %>

非常感谢帮助。

2 个答案:

答案 0 :(得分:1)

您需要使用params[:session][:remember_me]代替params[:remember_me]。将它与控制器的用户认证线进行比较。

答案 1 :(得分:0)

以下解决了我的问题

 def login(user)
    if params[:session][:remember_me] == "1"
    cookies.permanent.signed[:remember_token] = [user.id, user.password_salt]
    current_user = user
   elsif params[:session][:remember_me] == "0"
    cookies.signed[:remember_token] = [user.id, user.password_salt]
    current_user = user
   end
  end

视图:

    <%= form_for(:session, :url => sessions_path) do |f| %>
      <%= f.text_field :email, :placeholder => "Email" %>      
      <%= f.password_field :password, :placeholder => "Password" %>     
      Remember me? <%= f.check_box :remember_me %>
      <%= f.submit "Log in", :id => "login_submit" %>
      <% end %>