覆盖设计注册创建方法

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

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

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

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

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

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

而不是使用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 

如果您不想重写create方法的整个代码,只需在受保护的方法中设置资源变量 Devise :: RegistrationsController的 build_resource ,它在保存资源之前调用。

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