首页 > 解决方案 > 创建帐户时为另一个模型创建记录?

问题描述

我有一个多租户应用程序。创建帐户时,该帐户属于所有者,并且还会为所有者创建用户记录。此所有者可以通过成员资格加入表邀请其他用户。除帐户所有者外,所有用户都拥有该帐户的成员资格。

对于具有会员资格的用户(不是帐户所有者),显示 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

标签: ruby-on-railsrubydatabase

解决方案


你试过回调after_create吗?如果它有效,您将需要在客户端和管理员创建一个帐户,自我分配(管理员)反对创建分配(客户端)。

# models/account.rb
  after_create do
    self.memberships.create(user_id: self.owner, account_id: self.id)
  end

推荐阅读