设计:创建用户创建的额外记录

时间:2012-07-26 12:29:53

标签: ruby-on-rails devise has-and-belongs-to-many

如果用户使用设计创建帐户,如何创建额外记录?

在用户和团队模型之间使用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

2 个答案:

答案 0 :(得分:4)

我通过将routes.rb更改为指向自定义控制器来解决此问题。

的routes.rb

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

registrations_controller.rb

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

答案 1 :(得分: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