Rails 3: Best practices for saving models

拟墨画扇 提交于 2020-01-04 04:43:47

问题


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

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

  1. The model/method is responsible for calling save . So each method will just call self.save.
  2. The caller is responsible for calling save. So each method only updates the attributes but the caller calls user.save when it's done with the user.

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.

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.


回答1:


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


来源:https://stackoverflow.com/questions/12336163/rails-3-best-practices-for-saving-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!