【问题标题】:Rails 3.1 Mongoid has_secure_passwordRails 3.1 Mongoid has_secure_password
【发布时间】:2011-09-30 11:36:48
【问题描述】:

我正在尝试让 has_secure_password 与 mongoid 一起玩。我正在关注 Railscasts #270,但是当我使用用户名/密码登录时,出现错误:

undefined method `find_by_email' for User:Class

我看到一个类似的帖子 (http://stackoverflow.com/questions/6920875/mongoid-and-has-secure-password) 但是,按照它的建议完成后,我仍然遇到同样的错误。

这是我的模型:

class User 
  include Mongoid::Document
  include ActiveModel::SecurePassword 

  validates_presence_of :password, :on => :create
  attr_accessible :email, :password, :password_confirmation

  field :email, :type => String
  field :password_digest, :type => String
  has_secure_password
 end

控制器:

class SessionsController < ApplicationController

  def new
  end

  def create
    user = User.find_by_email(params[:email])
    if user && user.authenticate(params[:password])
      session[:user_id] = user.id
      redirect_to root_url, :notice => "Logged in!"
    else
      flash.now.alert = "Invalid email or password"
      render "new"
    end
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_url, :notice => "Logged out!"
  end

end

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.1 mongoid


    【解决方案1】:

    选项 1:在您的控制器中,您应该使用

    user = User.where(:email => params[:email]).first
    

    选项 2:在您的模型中,您应该定义

    def self.find_by_email(email)
      where(:email => email).first
    end
    

    【讨论】:

      【解决方案2】:

      Mongoid 不支持 find_by_attribute 方法。

      你最好改用where

      User.where(:email => email).all
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-03
        相关资源
        最近更新 更多