title: Adding records to multiple models in one transaction during create
body: <p>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?</p>
  
  <p>Here are my methods:</p>
  
  <pre><code>  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 =&gt; @user.id)
          @group = @account.groups.create(:name =&gt; 'Default', :user_id =&gt; @user)
          @group.members.create(:account_id =&gt; @account, :user_id =&gt; @user)
          Role.all.each do |role|
            @user.roles_users.create(:role_id =&gt; role.id, :account_id =&gt; @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
  </code></pre>
  
  <p>My models are:</p>
  
  <ul>
  <li>Account (has_many :users; :through account_users)</li>
  <li>User (has_one :profile)</li>
  <li>Accounts_User (belongs_to :account; belongs_to :user)</li>
  <li>Group (has_many :members, as: membership; belongs_to :user)</li>
  <li>Member (belongs_to :membership, :polymorphic => true)</li>
  <li>Profile (belongs_to :user)</li>
  <li>Roles (has_many :roles_users; has_many :users :through => :roles_users; has_many :accounts, :through => :roles_users)</li>
  <li>RolesUser (belongs_to :user; belongs_to :account; belongs_to :role)</li>
  </ul>