首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >防止Rails多次命中数据库

防止Rails多次命中数据库
EN

Stack Overflow用户
提问于 2013-06-07 05:37:35
回答 1查看 123关注 0票数 0

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

代码语言:javascript
复制
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

有没有一种更好的方法来做到这一点,而不会对数据库造成太大的影响?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-06-07 05:45:27

有一种更多的Rails方法可以通过使用validates_associated来完成激活。

但它访问数据库的次数并不多。您有四个表要更新或添加行,因此需要四个DB语句。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16972642

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档