我正在创建一个拥有用户和帐户的应用程序。我的问题是,我首先创建了用户模型和身份验证功能,然后意识到我需要用户属于帐户。
如果我在Route注册用户
http://lvh.me:3000/signup
它将创建一个新用户,发送激活电子邮件并激活一个用户。很好,除非它没有创造
Account
. 但现在,我需要添加一个
account
在混合物中。如果我在新路线注册
http://lvh.me:3000/accounts/new
它将创建帐户和用户,但我需要发送激活电子邮件,以便实际激活用户。我好像拿不到我的
帐户
控制器触发
@user.send_activation_email
在
create
我的行动
UserController
--请参见下面的代码。我知道下面的路不对,但我撞到了一堵砖墙,不知道从这里到哪里去。
用户.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
...
帐户.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
账户管理员.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
用户控制器.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
...