代码之家  ›  专栏  ›  技术社区  ›  Zabba fl00r

如何在用户注册时向用户添加用户配置文件?(设计,轨道3)

  •  3
  • Zabba fl00r  · 技术社区  · 15 年前

    我想推翻被设计的 RegistrationsContollers '创建操作,以便当用户注册时,我可以将 UserProfile 与该用户一起建模。

    因此,按照designe自述文件中的指导原则,我重写该操作:

    #File app/controllers/registrations_controller.rb:    
    class Users::RegistrationsController < Devise::RegistrationsController
      def create
        # some code here..
        self.user_profiles.build #Error (no method `user_profiles`)
        current_user.user_profiles.build #Error (current_user is nil)
        some other way???
      end
    end
    
    #File routes.rb:
    devise_for :users, :controllers => { :registrations => 'users/registrations' }
    

    设计人员正在 users 表,但是我如何关联 用户配置文件 有那个记录吗?

    我试过用谷歌搜索,但我就是没法用!任何帮助都非常感谢。

    (我现在在Rails3.0.3上使用Devise1.1.5)

    解决了的:

    添加有利于他人的解决方案:

    #File app/controllers/registrations_controller.rb:    
    class Users::RegistrationsController < Devise::RegistrationsController
      def create
        super
        @user.build_user_profile
        @user.user_profile.some_data = 'abcd'
        @user.save!
      end
    end
    
    1 回复  |  直到 15 年前
        1
  •  3
  •   scaney    15 年前

    self 引用此上下文中的控件而不是模型。

    另外,用户模型是否有许多用户配置文件?否则如果他们没有(他们只有一个),你就应该用 @user.build_user_profile ,不是 @user.user_profiles.build

    我还建议在模型级而不是控制器级使用回调函数,比如 before_create after_create ,即:

    class User < AR
        has_one :user_profile
    
        after_create :build_profile 
    
        def build_profile
            self.build_user_profile
            ...
        end
    end