修改后的Devise中的Nil Current_user创建操作

时间:2014-08-13 17:48:53

标签: ruby-on-rails devise

我为Devise创建了一个自定义注册控制器。我在表单中插入了一个参数,表示如果确实如此,我应该在注册后做一些额外的事情,例如,为用户创建一个相关的公司。

class RegistrationsController < Devise::RegistrationsController
  before_filter :authenticate_user!, :only => :token

  def new
    super
  end

  def create
    super
    reg_type = params['reg_type']
    if reg_type=='1'
      current_user.create_default_company!
    end    
  end

  def update
    super
  end

end 

但是,我的current_user现在没有了。

undefined method `create_default_company!' for nil:NilClass

在调用super之后,我可以使用什么来立即引用current_user,这会创建用户。

参数:

 Parameters: {"utf8"=>"✓", "authenticity_token"=>"E1urosfkmekwweklo/HZaEVrrmxQVKO9E=", "user"=>{"name"=>"", "email"=>"4@Gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up", "reg_type"=>"1"}

我使用两个链接传递参数:

new_user_registration_path(reg_type: '0')
new_user_registration_path(reg_type: '1')

创建的操作取决于用户选择的链接。

4 个答案:

答案 0 :(得分:1)

如果你打开devise gem,你会发现创建方法为

(设计-3.2.4)

 def create
    build_resource(sign_up_params)

    if resource.save
      yield resource if block_given?
      if resource.active_for_authentication?
        set_flash_message :notice, :signed_up if is_flashing_format?
        sign_up(resource_name, resource)
        respond_with resource, location: after_sign_up_path_for(resource)
      else
        set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format?
        expire_data_after_sign_in!
        respond_with resource, location: after_inactive_sign_up_path_for(resource)
      end 
    else
      clean_up_passwords resource
      respond_with resource
    end 
  end

您应首先检查您正在使用的设备版本,然后您可以在控制器中覆盖该方法。

简而言之,使用资源而不是current_user可以解决您的问题,但它可能会生成不适当的结果,因为您只会在渲染模板后分配属性(而不是保存)。

答案 1 :(得分:1)

您应该可以通过将块传递给super来访问新用户:

def create
   super do |resource|
     if params['reg_type'] == "1"
        resource.create_default_company!
      end
    end
  end

docs&#34;配置控制器&#34;下解释了这一点(好吧,至少提到)。

可以通过块参数resource访问新用户,但此时可能无法保存。

答案 2 :(得分:1)

您可以在reg_type回调中查看此after_create参数,然后创建默认公司(如果它等于'1'

答案 3 :(得分:0)

首先,感谢您的所有评论。我的解决方案是使用andrey deineko建议和after_create回调。我添加了一个attr_accessor来引用权限,我将其作为隐藏字段添加到表单中。

我用过..

class User < ActiveRecord::Base

  attr_accessor :reg_type
  after_create  :create_default_company!, if: :is_reg?

 def is_reg?
    @reg_type == '1'
  end
...

end

似乎运作良好。谢谢你提出的所有建议。

相关问题