覆盖设计注册创建方法

Vas*_*rth 16 overriding ruby-on-rails crud devise

我想在创建用户时专门设置一个字段.我有

class RegistrationsController < Devise::RegistrationsController
  def create
    super
    @user.tag_list = params[:tags]
  end
end
Run Code Online (Sandbox Code Playgroud)

我有传递tags参数的复选框,我已在服务器日志中验证了tags参数是否正在传递.但是,当我在控制台中调用@ user.tag_list时,我只得到一个空白的响应[].

我觉得问题在于我操纵设计的创造方法.我没有明确地在任何地方设置@user,但我不确定如何使用Devise设置它.有人在使用设计时知道如何设置特定字段吗?

str*_*ics 50

对于在搜索如何覆盖设计方法时发现这一点的任何人的未来参考,大多数Devise方法接受一个块,所以这样的东西也应该工作:

class RegistrationsController < Devise::RegistrationsController
  def create
    super do
        resource.tag_list = params[:tags]
        resource.save
    end
  end
end
Run Code Online (Sandbox Code Playgroud)


Pun*_*eth 12

而不是使用super调用Devise :: RegistrationsController的创建操作,将其替换为Devise :: RegistrationsController的create方法实际代码

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
Run Code Online (Sandbox Code Playgroud)


小智 8

如果你不希望重写create方法的全部代码,你可以简单地设置保护法里面的资源变量:build_resource设计:: RegistrationsController,保存资源之前被调用.

protected 

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