Devise/Rrails成功注册后自动添加Profile对象



我很难弄清楚如何在用户使用design注册后立即自动创建用户配置文件对象。我的概要文件对象已经搭建好了,现在需要将空的profile.new对象添加到用户对象中。以下代码来自registrations_controller.rb

  protected
  # If you have extra params to permit, append them to the sanitizer.
  def configure_sign_up_params
    devise_parameter_sanitizer.for(:sign_up) << :profile_id
  end
  # The path used after sign up.
  def after_sign_up_path_for(resource)
    p "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"
    resource.profile << Profile.new
    p resource
    super(resource)
  end

结果是,在Rails控制台中,p'$$$$..'行是可见的,并没有错误。然而,在psql中,当查看profile_id时,它是null。我已经挠头好几个小时了,这是最好的方法吗,把它传给魔鬼队的桑蒂泽?

我们确实想过重定向到搭建好的create_profile视图,但在用户注册后没有完成配置文件的情况下,我们会遇到问题。有人对如何继续或如何传入新的Profile对象有什么建议吗?

为什么要在Userprofile属性中添加Profile.new(假设resource模型是User)?

假设每个User:只有一个Profile

resource.profile = Profile.new
resource.save # you need to save the resource as well
super(resource)

就是你想要的。

然而,正如Sylvain所指出的,您实际上希望使用after_create过滤器从User模型本身处理此问题:在创建用户后立即附加配置文件。无需修改控制器代码。

您可以尝试在用户模型中添加一个方法

 after_create :create_profile
 private
 def create_profile
      self.profiles.build(#something)
      #according there is a link between your profiles object and user
 end

希望这能帮助

相关内容

最新更新