0

我正在开发一个具有用户模型的网络应用程序。您可以注册或试用该应用程序并成为“客人”。在添加访客选项之前,我的注册功能运行良好。我基于 Railscast 来做到这一点(http://railscasts.com/episodes/393-guest-user-record),那是我遇到麻烦的时候

这是我的用户模型代码

class User < ActiveRecord::Base

  attr_accessible :name, :email, :password, :password_confirmation
  has_many :bookings
  has_one :account, dependent: :destroy

  # before_save :downcase_email, allow_nil: true
  before_save :create_remember_token
  validates_presence_of :name, :email, :password, :password_confirmation, unless: :guest?
  validates_uniqueness_of :email, case_sensitive: false , allow_blank: true   
  validates :name, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, format:     { with: VALID_EMAIL_REGEX }, unless: :guest?
  validates :password, length: { minimum: 6 },  unless: :guest?

  def downcase_email
    { |user| user.email = email.downcase }
  end

  # has_secure_password
  # override has_secure_password to customize validation until Rails 4.
  require 'bcrypt'
  attr_reader :password, :password_confirmation
  include ActiveModel::SecurePassword::InstanceMethodsOnActivation

  ##def to_param
  ##  "#{id}.#{name.parameterize}"
  ##end

  def self.new_guest
   new { |u| u.guest = true }
  end

  def name
    guest ? "Guest" : name
  end

  private

    def create_remember_token
      self.remember_token = SecureRandom.urlsafe_base64
    end
end

这是我的用户控制器代码:

class UsersController < ApplicationController

  before_filter :signed_in_user, only: [:edit, :update]
  before_filter :correct_user,   only: [:edit, :update]

  def show
    @user = User.find(params[:id])
  end

  def new
    @user = User.new
  end

  def create
    @user = params[:user] ? User.new(params[:user]) : User.new_guest
    if @user.save
      sign_in @user
      @user.create_account.accountPlan = "Free"
      ##flash[:success] = "Welcome to the HighTide!"
        redirect_to @user
    else
        render 'new'
    end
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(params[:user])
      #flash[:success] = "Profile updated"
      sign_in @user
      redirect_to @user
    else
      render 'edit'
    end
  end


  private

    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_path) unless current_user?(@user)
    end

    def admin_user
      redirect_to(root_path) unless current_user.admin?
    end

end

你可能会注意到一些代码被注释掉了。我无法在没有电子邮件的情况下将用户存储在数据库中(并且现在有一个快速而肮脏的工作,我评论了回调 before_save,我还可以补充一点,我使用 Michael Hartl tut 的指导方针)

发生的情况是,当我运行此代码时,我得到一个unknown attribute: password_confirmation error,但是当我注释掉

  require 'bcrypt'
  attr_reader :password, :password_confirmation
  include ActiveModel::SecurePassword::InstanceMethodsOnActivation

并使用has_secure_password instead

我的堆栈级别太深

我还没想好该怎么做

4

0 回答 0