Adding records to multiple models in one transaction during create
===

I have the following new and create actions.  They are used to create a new account in a multi-tenant app.  It works fine but even as a newbie I know this is not correct.  Here is my question, how can I make the create action more thin so it follows best practices?  And, how can I make so that all the queries submit under one transaction?

Here are my methods:

      def new
        @account = Account.new
        @user = @account.users.build()
        @account.accounts_users.build()
        respond_to do |format|
          format.html # new.html.erb
          format.json { render json: @account }
        end
      end

  

      def create
        @account = Account.new(params[:account])
        respond_to do |format|
          if @account.save
             @user = User.find_by_email(params[:account][:users_attributes]["0"][:email])
            Profile.create(:user_id => @user.id)
            @group = @account.groups.create(:name => 'Default', :user_id => @user)
            @group.members.create(:account_id => @account, :user_id => @user)
            Role.all.each do |role|
              @user.roles_users.create(:role_id => role.id, :account_id => @account)
            end
  
            flash[:domain] = @account.subdomain
            format.html { redirect_to thanks_url }
            format.json { render json: @account, status: :created, location: @account }
          else
            format.html { render action: "new" }
            format.json { render json: @account.errors, status: :unprocessable_entity }
          end
        end
      end

My models are:

 - Account (has_many :users; :through account_users)
 - User (has_one :profile)
 - Accounts_User (belongs_to :account; belongs_to :user)
 - Group (has_many :members, as: membership; belongs_to :user)
 - Member (belongs_to :membership, :polymorphic => true)
 - Profile (belongs_to :user)
 - Roles (has_many :roles_users; has_many :users :through => :roles_users; has_many :accounts, :through => :roles_users)
 - RolesUser (belongs_to :user; belongs_to :account; belongs_to :role)