在Devise / Rails成功注册后自动添加配置文件对象

时间:2016-03-23 17:23:01

标签: ruby-on-rails ruby-on-rails-3 devise

在用户使用设备注册时,我无法确定如何自动创建用户配置文件对象。我的配置文件对象已被搭建,现在是将空的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。我一直在摸不着头几个小时,这是通过将它传递到Devise的santizer中的最佳方法吗?

我们确实考虑重定向到脚手架的create_profile视图,但是如果用户注册然后没有完成配置文件,我们就会遇到问题。有没有人对如何继续,或如何传递新的Profile对象有任何建议?

2 个答案:

答案 0 :(得分:1)

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

 after_create :create_profile

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

希望这有帮助

答案 1 :(得分:1)

为什么要在Profile.new的{​​{1}}属性中添加User(假设profile模型是resource)?

假设每User只有一个Profile

User

...就是你想要的。

但是,正如Sylvain所指出的,您实际上希望使用resource.profile = Profile.new resource.save # you need to save the resource as well super(resource) 过滤器从User模型本身处理此问题:在创建用户后立即附加配置文件。无需修改控制器代码。