【问题标题】:undefined method `attributes' for nil:NilClass - Wicked/Devise gemsnil 的未定义方法“属性”:NilClass - Wicked/Devise gems
【发布时间】:2016-05-12 14:40:06
【问题描述】:

我正在尝试使用 Devise 实现 Wicked gem,因为我希望用户通过不同的步骤来完成他们的个人资料。我是一个完全的新手,所以如果你能给我一个关于可能是什么问题的建议,我将不胜感激。

我遇到的错误是这个错误,当我尝试从“个人”步骤继续到“风格”步骤时它会显示出来。我猜这是保存数据的问题:

NoMethodError in OnboardingController#update

undefined method `attributes' for nil:NilClass
 **@user.attributes(user_params)**

这些是我的注册和入职控制器:

class RegistrationsController < Devise::RegistrationsController


  protected 

  def after_sign_up_path_for(resource)
    '/onboarding/personal'
  end

  def after_update_path_for(resource)

    registration_steps_path

  end

  def new 

  super

  end



  def create

  super

  end



  def update 

  super

  end



  def update_resource(resource, params)
    if resource.encrypted_password.blank? # || params[:password].blank?
      resource.email = params[:email] if params[:email]
      if !params[:password].blank? && params[:password] == params[:password_confirmation]
        logger.info "Updating password"
        resource.password = params[:password]
        resource.save
      end
      if resource.valid?
        resource.update_without_password(params)
      end
    else
      resource.update_with_password(params)
    end
  end
end

class OnboardingController < ApplicationController
    include Wicked::Wizard
    steps :personal, :stylefirst


    def show
        @user = current_user
    render_wizard

    end

     def update

  @user = current_user

  @user.attributes(user_params)

  render_wizard @user

     end


end

【问题讨论】:

  • 错误告诉你,在载入控制器的更新操作中不存在 current_user。
  • 嗯,但你可以看到它确实存在......
  • 不,我们看不到。可能是用户根本没有登录。
  • 是因为认证,谢谢!但现在我在同一行收到一个新错误:ActiveModel::ForbiddenAttributesError

标签: ruby-on-rails devise wicked-gem


【解决方案1】:

使用 Devise,如果没有用户登录,current_usernil。所以您的问题是您在 update 操作上分配 @user = current_user 而不验证用户是否已登录。

如果您想确保 update 操作仅对登录用户可用,请使用 Devise 提供的 authenticate_user! 辅助操作:

class OnboardingController < ApplicationController
   before_filter :authenticate_user!, only: [:edit, :update]

   # ...
end

authenticate_user! 帮助方法将在用户未登录时将用户重定向到登录页面。如果用户成功登录,将设置 current_user 并将他们重定向回原来的页面尝试访问。

【讨论】:

  • 是因为认证,谢谢!但现在我在同一行收到一个新错误:ActiveModel::ForbiddenAttributesError
  • 您需要使用强参数将您从表单中传递的参数列入白名单:edgeguides.rubyonrails.org/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-16
  • 1970-01-01
相关资源
最近更新 更多