为什么acts_as_paranoid打破了我的模特?

时间:2014-09-17 01:11:32

标签: ruby-on-rails ruby session-variables acts-as-paranoid

我最近将"偏执" gem添加到我项目的User model。该模型还使用"has_secure_password";完全有效,直到我将"acts_as_paranoid"放在User model的顶部。现在我得到以下参数错误:

Started GET "/users/8/edit" for 127.0.0.1 at 2014-09-16 20:57:48 -0400
Processing by UsersController#edit as HTML
  Parameters: {"id"=>"8"}
Completed 500 Internal Server Error in 5ms

ArgumentError (wrong number of arguments (0 for 1)):
  app/models/user.rb:19:in `hash'
  app/helpers/sessions_helper.rb:25:in `current_user'
  app/helpers/sessions_helper.rb:11:in `signed_in?'
  app/helpers/sessions_helper.rb:33:in `signed_in_user'

任何想法都将不胜感激。

这是我的用户模型:

class User < ActiveRecord::Base
  acts_as_paranoid
  before_save { self.email = email.downcase }
    before_create :create_remember_token

    validates :name, presence: true, length: { maximum: 50 }
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
    validates :password, length: { minimum: 6 }
    validates_inclusion_of :status, :in => ['active', 'inactive']
    has_secure_password


    def User.new_remember_token
        SecureRandom.urlsafe_base64
    end

    def User.hash(token)
        Digest::SHA1.hexdigest(token.to_s)
    end

private

    def create_remember_token
      self.remember_token = User.hash(User.new_remember_token)
    end

end

这是我的会话助手:

module SessionsHelper

  def sign_in(user)
    remember_token = User.new_remember_token
    cookies.permanent[:remember_token] = remember_token
    user.update_attribute(:remember_token, User.hash(remember_token))
    self.current_user = user
  end

  def signed_in?
    !current_user.nil?
  end


  def current_user=(user)
    @current_user = user
  end

  def current_user
    @current_user     
  end

   def current_user
    remember_token = User.hash(cookies[:remember_token])
    @current_user ||= User.find_by(remember_token: remember_token)
  end

  def current_user?(user)
    user == current_user
  end

  def signed_in_user
    unless signed_in?
      store_location
      redirect_to signin_url, notice: "Please sign in."
    end
  end

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

  def redirect_back_or(default)
    redirect_to(session[:return_to] || default)
    session.delete(:return_to)
  end

  def store_location
    session[:return_to] = request.url if request.get?
  end

end

1 个答案:

答案 0 :(得分:1)

User.hash by convention of its parent class不接受任何参数,应返回Fixnum

它用于整个Ruby语言中其他类的对象比较,例如在Hash中查找键的值时。如果a.eql?(b),那么a.hash == b.hash也必须为真。

解决此问题的最佳方法是将您的hash方法重命名为其他方法,而不是妨碍Ruby约定。