2012-04-12 77 views
12

我想在创建用户时专门设置一个字段。我有覆盖设计注册创建方法

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

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

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

+2

Planetpluto,你应该添加自己的答案,使用'resource'并将其标记为答案,正如你在你的评论Puneeth中提到的那样。这是一个更好,更简单的解决方案。 – Jeff 2013-09-26 19:54:20

回答

39

取代它的​​人谁发现这一点的同时搜索以供将来参考如何重写设计方法,大部分设计方法接受一个块,所以这样的事情应该工作以及:

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

它没有为我工作(Rails 3.2),我已经切换到一个超级,然后我的指令 – OWZY 2015-06-04 18:02:59

+0

工作在Rails 5.1上。 – 2017-07-17 13:38:06

10

而不是使用super调用设计:: RegistrationsController的创建行动,与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 
+1

谢谢,这个作品完美。我将尝试使用super和它下面,而不是@ user.tag_list resource.tag_list,看看是否也可以。 – Vasseurth 2012-04-15 20:22:04

+0

对不起,重新访问这样一个旧的线程,但Puneeth,你能解释为什么最好把Devise的create方法中的实际代码放进去,而不是使用'super'? – jeffdill2 2015-02-11 21:25:02

+0

@streetlogics回答更好地解决了这个问题。该设计创建超级有这条线“产量资源,如果block_given?”这将评估在他的例子中添加的块。 – blnc 2015-03-11 16:42:04

6

如果您不希望重写create方法的全部代码,你可以简单的设置prote内部资源变量cted方法:build_resource of Devise :: RegistrationsController,在资源被保存之前调用。

protected 

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

这在Rails 4 w/Devise 3.5中适用于我。谢谢!!!!!! – cman77 2017-02-17 20:02:47

+1

与接受的答案有问题触发我的验证两次,这种方法带来了一种新的方法来实现,谢谢。 – ollaollu 2017-04-09 19:35:38