我有一个多租户应用程序。创建帐户后,该帐户属于所有者,并且还为所有者创建用户记录。该所有者可以通过成员资格加入表邀请其他用户。除帐户所有者外,所有用户均具有该帐户的成员资格。
对于具有成员身份的用户(不是帐户所有者),将显示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
似乎无效。
控制器
user.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
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
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
模型
user.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
account.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
membership.rb
class Membership < ApplicationRecord
belongs_to :account
belongs_to :user
end
答案 0 :(得分:0)
您是否尝试过回调after_create
?
如果可行,您将需要在客户端上找到它,然后由admin创建一个帐户,并在创建分配(客户端)时进行自我分配(admin)。
# models/account.rb
after_create do
self.memberships.create(user_id: self.owner, account_id: self.id)
end
答案 1 :(得分:0)
最终通过将以下行放在= simple_form_for([@property, @downtown]) do |f|
= f.input :name
= f.input :last_remodel
= f.input :original_construction_year
下来回答此问题:
if @account.save
可能不理想,但目前可以使用。不过,我最终可能会为此提供服务或类似的服务。