代码之家  ›  专栏  ›  技术社区  ›  Charles Smith

从一个控制器调用Rails 5操作到另一个控制器

  •  0
  • Charles Smith  · 技术社区  · 6 年前

    我正在创建一个拥有用户和帐户的应用程序。我的问题是,我首先创建了用户模型和身份验证功能,然后意识到我需要用户属于帐户。

    如果我在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
      ...
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   user229044    6 年前

    如果您需要将这两个模型都创建为注册流的一部分,那么在一个控制器中有一个操作可以触发注册流并创建这两个记录。

    您可以通过多种方式实现这一点,例如 Users#signup 操作在事务中创建用户和帐户,或者您可以将该逻辑移出控制器并移入模型层,并提供 User.signup 方法,该方法显式或在 after_create 回拨。

    不管怎样,这里的解决方法都是简化和统一注册流程,而不是将其拆分为多个控制器。只有当您有某种需要用户在步骤之间执行某些操作的多步骤注册时,才需要这样做。