ruby-on-rails - 创建帐户时为另一个模型创建记录?
问题描述
我有一个多租户应用程序。创建帐户时,该帐户属于所有者,并且还会为所有者创建用户记录。此所有者可以通过成员资格加入表邀请其他用户。除帐户所有者外,所有用户都拥有该帐户的成员资格。
对于具有会员资格的用户(不是帐户所有者),显示 account/users/:id 显示页面。我希望帐户所有者也能这样做,但收到以下错误消息:
ActiveRecord::RecordNotFound in Accounts::UsersController#show
Couldn't find User with 'id'=2 [WHERE "memberships"."account_id" = $1]
def show
@user = current_account.users.find(params[:id])
end
我可以在管理面板中向所有者用户添加会员资格,并且此错误消失了,但是我想在所有者/用户创建帐户时将会员资格添加到他们。
有任何想法吗?
在下面的帐户控制器中添加@account.memberships.build(user_id: current_user, account_id: current_account)
之前if @account.save
似乎不起作用。
控制器
用户.rb
module Accounts
class UsersController < Accounts::BaseController
before_action :authorize_owner!, only: [:edit, :show, :update, :destroy]
def show
@user = current_account.users.find(params[:id])
end
def destroy
user = User.find(params[:id])
current_account.users.delete(user)
flash[:notice] = "#{user.email} has been removed from this account."
redirect_to users_path
end
end
end
account_controller.rb
class AccountsController < ApplicationController
def new
@account = Account.new
@account.build_owner
end
def create
@account = Account.new(account_params)
if @account.save
sign_in(@account.owner)
flash[:notice] = "Your account has been created."
redirect_to root_url(subdomain: @account.subdomain)
else
flash.now[:alert] = "Sorry, your account could not be created."
render :new
end
end
private
def account_params
params.require(:account).permit(:name, :subdomain,
{ owner_attributes: [:email, :password, :password_confirmation
]}
)
end
end
楷模
用户.rb
class User < ApplicationRecord
has_many :memberships
has_many :accounts, through: :memberships
def owned_accounts
Account.where(owner: self)
end
def all_accounts
owned_accounts + accounts
end
end
帐号.rb
class Account < ApplicationRecord
belongs_to :owner, class_name: "User"
accepts_nested_attributes_for :owner
validates :subdomain, presence: true, uniqueness: true
has_many :memberships
has_many :users, through: :memberships
end
会员资格.rb
class Membership < ApplicationRecord
belongs_to :account
belongs_to :user
end
解决方案
你试过回调after_create
吗?如果它有效,您将需要在客户端和管理员创建一个帐户,自我分配(管理员)反对创建分配(客户端)。
# models/account.rb
after_create do
self.memberships.create(user_id: self.owner, account_id: self.id)
end
推荐阅读
- jq - 当您解析字段值以更新字段时如何更新 jq 中的字段值(也就是重新格式化值)
- java - 如何在 DOTENV 文件中存储加密密钥?
- python - 未调用的函数在变量在外部时运行,但除非在变量在内部时调用,否则不会运行
- linux - 我想制作一个可以切换用户和删除日志文件的python脚本
- javascript - 在 Handlebars 中查找部分动态路径
- r - 将 R summarise() 与 group_by() 一起使用,同时引用其他列
- docker - 尝试访问我的主机文件中设置的本地 IP 地址时出现 ERR_CONNECTION_REFUSED
- javascript - 模态javascript代码只能暂时工作?
- webpack - 为什么 webpack 在 Next.js 应用程序中保持下载?
- list - 在 PowerApps 中构建电子邮件家庭电子邮件功能