我正在构建一个Ruby on Rails应用程序,其中researchers
可以运行studies
。
我希望在首次注册时为研究人员(用户)创建一个新的样本研究。这与db种子有点不同,因为它需要为这个特定用户动态创建研究,而不是整个数据库一次。
我正在将Devise用于用户帐户。
这有什么好方法?谢谢!
答案 0 :(得分:2)
您可以通过覆盖 Devise::RegistrationsController
Devise::InvitationsController
来完成。
# feel free to call this class whatever you want.
class Users::InvitationsController < Devise::InvitationsController
def create
# the block is yielded after the resource has been saved
# but before anything has been rendered.
super do |user|
if user.valid?
user.studies.create(title: 'New study')
end
end
end
end
然后我们需要告诉Devise路由到我们的自定义控制器:
# config/routes.rb
devise_for :users, controllers: {
registrations: 'users/registrations',
invitations: 'users/invitations'
}
如果要从控制器中提取创建过程,可以使用工厂方法或service object:
class Study < ActiveRecord::Base
# ...
def self.create_default(**kwargs)
# the default options are merged with the keyword arguments
attrs = {
title: 'Foo',
bar: 'Baz'
}.merge(kwargs)
study = scoped.build(attrs)
# lets us pass a block just like .new and .create
yield study if block_given?
study
end
end
# app/controllers/user/registrations_controller.rb
# ...
def create
# the block is yielded after the resource has been saved
# but before anything has been rendered.
super do |user|
if user.valid?
study = user.studies.create_default(baz: 'Something else')
study.save
end
end
end
答案 1 :(得分:1)
配置/ routes.rb中
devise_for :users, :controllers => { :sessions => "sessions" }
应用程序/控制器/ sessions_controller.rb
class SessionsController < Devise::SessionsController
before_action :before_login, only: :create
after_action :after_login, only: :create
def before_login
end
def after_login
if current_user.sign_in_count == 1
User.studies.create(title: 'New study')
end
end
end