保存模型的最佳实践

保存模型的最佳实践

本文介绍了Rails 3:保存模型的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该什么时候将模型保存在 Rails 中?谁应该负责调用 save、模型本身或调用者?

When should I save my models in rails? and who should be responsible for calling save, the model itself, or the caller?

假设我的用户模型中有诸如 udpate_pointsupdate_level 等(公共)方法.有两个选项:

Lets say I have (public)methods like udpate_points, update_level, etc. in my user model. There are 2 options:

  1. 模型/方法负责调用 save .所以每个方法都会调用 self.save.
  2. 调用者负责调用保存.所以每个方法只更新属性,但调用者在用户完成后调用 user.save.

权衡是相当明显的:在选项 #1 中,模型保证会保存,但我们在每个事务中多次调用保存.在选项 #2 中,我们每个事务只调用一次 save,但调用者必须确保调用 save.例如 team.leader.update_points 需要我调用 team.leader.save 这有点不直观.如果我有多个方法在同一个模型对象上运行,这会变得更加复杂.

The tradeoffs are fairly obvious:In option #1 the model is guaranteed to save, but we call save multiple times per transaction.In option #2 we call save only once per transaction, but the caller has to make sure to call save. For example team.leader.update_points would require me to call team.leader.save which is somewhat non-intuitive. This can get even more complicated if I have multiple methods operating on the same model object.

根据请求添加更具体的信息:update level 看用户有多少积分,更新用户的等级.该函数还会调用 facebook api 以通知它用户已达到新级别,因此我可能会将其作为后台作业有效地执行.

Adding a more specific info as per request:update level looks at how many points the users has and updates the level of the user. The function also make a call to the facebook api to notify it that the user has achieved an new level, so I might potently execute it as a background job.

推荐答案

我最喜欢的实现此类内容的方法是使用 attr_accessors 和模型挂钩.下面是一个例子:

My favorite way of implementing stuff like this is using attr_accessors and model hooks. Here is an example:

class User < ActiveRecord::Base
  attr_accessor :pts

  after_validation :adjust_points, :on => :update

  def adjust_points
    if self.pts
      self.points = self.pts / 3 #Put whatever code here that needs to be executed
    end
  end
end

然后在您的控制器中执行以下操作:

Then in your controller you do something like this:

def update
  User.find(params[:id]).update_attributes!(:pts => params[:points])
end

这篇关于Rails 3:保存模型的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 00:02