0

下面的方法在保存帐户、保存用户、使用帐户 ID 更新单元时、创建新的 unit_users 记录(将单元与用户关联)时命中数据库。所以这至少是它访问数据库的 4 次:

def activate_new_account(assign_units = [])
    account = Account.new(
                          :name             => self.name,
                          :email            => self.email,
                          :phone            => self.phone,
                          :street_address   => self.street_address,
                          :city             => self.city,
                          :state            => self.state,
                          :postal_code      => self.postal_code,
                          :country          => self.country)
    errors.clear

    error_msgs = []

    transaction do
      if account.valid?
        account.save

        user  = User.new(:name                  => self.name,
                         :email                 => self.email,
                         :password              => self.password,
                         :password_confirmation => self.password_confirmation,
                         :phone                 => self.phone,
                         :address               => formatted_address,
                         :role_id               => self.user_role_id,
                         :account_id            => account.id)

        if user.valid?          
          user.save

          if units_for_account            
            begin
              units = Unit.find(units_for_account.split(" "))
              units.each do |unit|
                #hitting database twice
                unit.update_attributes account_id: account.id
                unit.users << user
              end

            rescue ActiveRecord::RecordNotFound
              error_msgs << "Couldn't find all Units with serial numbers: #{units_for_account.split(' ')}"
            rescue ActiveRecord::RecordInvalid => invalid
              error_msgs << invalid.record.errors
            end            
          end

        else
          account.destroy
          error_msgs << user.errors.full_messages
        end  
      else    
        error_msgs << account.errors.full_messages
      end
    end

    if error_msgs.size > 0
      error_msgs.each do |error|
        errors.add :base, error
      end
      return false
    end

    return true
end

有没有更多的 Railsy 方法来做到这一点而不会过多地访问数据库?

4

1 回答 1

0

有更多的 Rails 方法来完成激活,使用validates_associated.
但它不会少访问数据库。您有四个表要更新或添加行,因此您需要四个 DB 语句。

于 2013-06-06T21:45:27.337 回答