1

当用户使用 devise 创建帐户时,如何创建额外记录?

使用用户和团队模型之间的 HABTM 关联,​​我正在尝试创建一个与用户相关联的团队,以便在那里创建帐户。

下面是我尝试使用的代码。

class RegistrationsController < Devise::RegistrationsController
  def create
    super
    current_user.teams.create(:name => 'User Name')
  end
end

我也试过这个

class RegistrationsController < Devise::RegistrationsController
def create

    build_resource

        if resource.save
        resource.teams.create(:name => 'User Name')
        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
    end
end
4

2 回答 2

4

我通过更改 routes.rb 以指向自定义控制器解决了这个问题。

路线.rb

devise_for :users,
           :controllers => { :registrations => "registrations" }

注册控制器.rb

class RegistrationsController < Devise::RegistrationsController
   def create
     super
     resource.teams.create(:name => 'User Name')    
   end
end
于 2012-07-26T13:50:50.860 回答
1

您可以像这样在模型中使用 before_save:

class User < ActiveRecord::Base
  # ... your code ...
  after_create :set_user_on_team
  # ... your code ...
  private
    def set_user_on_team
      teams.create(:name => username)
    end
end

请参阅此处的文档:http: //guides.rubyonrails.org/active_record_validations_callbacks.html#available-callbacks

于 2012-07-26T13:11:25.060 回答