在Devise注册后自动创建的用户配置文件不会显示在布局部分中

时间:2011-09-09 02:53:38

标签: ruby-on-rails model-view-controller authentication devise

我想在用户使用Devise注册我的网站后创建个人资料。所以在User模型中,我添加: after_create :build_spec

def build_spec
  Spec.new(:user_id => :id)
end

我还有一个views / layouts / _header.html.erb,它有一个指向Spec的链接:

<%= link_to "Profile", spec_path(Spec.find_by_user_id(current_user.id)) %>

当用户刚刚完成注册表单并单击注册按钮时,这会产生麻烦。他将被引导到某个页面。此时,我认为尚未创建此用户的Spec对象,因此_header部分中的链接不起作用(nil对象),并且用户收到错误:

No route matches {:action=>"show", :controller=>"specs"}

(显然,我的SpecsController有动作“show”)

我的问题是:如何在注册后将注册用户重定向到第一页之前为注册用户创建规范(为了使链接到规范工作)?

非常需要评论和建议。

1 个答案:

答案 0 :(得分:1)

覆盖Devise RegistrationsController中的after_sign_up操作。

https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-on-successful-sign-up-%28registration%29

那将是这样的:

class RegistrationsController < Devise::RegistrationsController
protected

  def after_sign_up_path_for(resource)
    Spec.create(:user_id => resource.id)
    after_sign_in_path_for(resource)
  end
end

然后,如果您刚刚将Spec.new(:user_id => :id) 替换为Spec.create(:user_id => :id),那么您的方法也可以正常工作 Spec.new只是创建一个新的Spec实例,但实际上并没有保存它。

相关问题