Overriding Devise Registration Create Method

泪湿孤枕 提交于 2019-12-18 12:55:09

问题


I want to specifically set a field when a user is created. I have

class RegistrationsController < Devise::RegistrationsController
  def create
    super
    @user.tag_list = params[:tags]
  end
end

I have check boxes that pass the tags parameter and I have verified in the server logs that the tags parameter is being passed. However, when I call @user.tag_list in the console I just get a blank response [] .

I feel that the problem lies in my manipulating of the create method of devise. I have not explicitly set @user anywhere but am not sure how to set it using Devise. Does anyone know how to set a specific field when using devise?


回答1:


For future reference for anyone who finds this while searching for how to override devise methods, most of the Devise methods accept a block, so something like this should work as well:

class RegistrationsController < Devise::RegistrationsController
  def create
    super do
        resource.tag_list = params[:tags]
        resource.save
    end
  end
end



回答2:


Instead of using super to invoke the Devise::RegistrationsController's create action, replace it with the actual code of Devise::RegistrationsController's create method

build_resource
resource.tag_list = params[:tags]   #******** here resource is user 
if resource.save
  if resource.active_for_authentication?
    set_flash_message :notice, :signed_up if is_navigational_format?
    sign_in(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_navigational_format?
    expire_session_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



回答3:


If you don't want to rewrite the entire code of the create method, you can simply set the resource variable inside the protected method :build_resource of Devise::RegistrationsController, which is called before the resource is saved.

protected 

# Called before resource.save
def build_resource(hash=nil)
  super(hash)
  resource.tag_list = params[:tags]
end


来源:https://stackoverflow.com/questions/10117045/overriding-devise-registration-create-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!