我正在创建一个包含用户和帐户的应用程序。我的问题是我首先创建了用户模型和身份验证功能,但后来意识到我需要让用户属于帐户。
如果我在路线http://lvh.me:3000/signup
注册用户,它将创建新用户,发送激活电子邮件并激活用户。除了没有创建Account
之外,效果很好。但现在,我需要在混合中添加account
。如果我在我的新路线http://lvh.me:3000/accounts/new
注册,它将创建帐户和用户,但我需要发送激活电子邮件,以便我可以实际激活用户。我似乎无法让我的Account
控制器在@user.send_activation_email
内的create
操作中触发UserController
- 请参阅下面的代码。我知道下面的方式不是正确的方法,但是我碰到了一堵砖墙,不知道从哪里开始。
user.rb
class User < ApplicationRecord
has_many :memberships
has_many :accounts, through: :memberships
accepts_nested_attributes_for :accounts
...
# Sends activation email.
def send_activation_email
UserMailer.account_activation(self).deliver_now
end
...
account.rb
class Account < ActiveRecord::Base
belongs_to :owner, class_name: 'User'
accepts_nested_attributes_for :owner
has_many :memberships
has_many :users, through: :memberships
end
accounts_controller.rb
class AccountsController < ApplicationController
def new
@account = Account.new
@account.build_owner
end
def create
@account = Account.new(account_params)
if @account.save
@user.send_activation_email
flash[:info] = 'Please check your email to activate your account.' # Use this for registered users
# flash[:info] = 'Please have user check their email to activate their account.' # Use this for admin created users
redirect_to root_url
else
flash.now[:alert] = 'Sorry, your account could not be created.'
render :new
end
end
private
def account_params
params.require(:account).permit(:organization, owner_attributes: [:name, :email, :password, :password_confirmation])
end
end
users_controller.rb
class UsersController < ApplicationController
...
def create
@user = User.new(user_params)
if @user.save
@user.send_activation_email
flash[:info] = 'Please check your email to activate your account.' # Use this for registered users
# flash[:info] = 'Please have user check their email to activate their account.' # Use this for admin created users
redirect_to root_url
else
render 'new'
end
end
...
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation, accounts_attributes: [:organization])
end
...
答案 0 :(得分:2)
如果您需要在注册流程中创建两个模型,则在单个控制器中执行单个操作,以触发注册流并创建两个记录。
您可以通过多种方式实现此目的,例如让Users#signup
操作创建用户和事务中的帐户,或者您可以将该逻辑移出控制器并进入模型层并提供User.signup
方法,可以明确地或在after_create
回调中创建帐户。
无论哪种方式,此处的修复方法是简化和统一您的注册流程,而不是将其拆分为多个控制器。如果您有某种需要用户在步骤之间执行某些操作的多步注册,您只需要这样做。