how to transfer this code to model?
I have a code which calculates a parameter in the create action and update action differently. Here expiry_time is the column in the db and expiry_duration is a virtual parameter.
class SomeController
def create
params[:model][:expiry_time] = Time.now + params[:model][:expiry_duration].to_i
@model = Model.new(param开发者_JAVA技巧s[:model])
if @model.save
redirect_to ..
else
render ..
end
end
def update
@model = Model.find(params[:id])
params[:model][:expiry_time] = @model.created_at + params[:model][:expiry_duration].to_i
if @model.update_params(params[:model])
redirect_to ..
else
render ..
end
end
end
I was thinking of moving the calculation part to model in a before_save function. Should I check for the id there to decide if it is a new record or an existing one like this?
class Model
before_save :update_expiry_time
def update_expiry_time
start_time = id ? created_at : Time.now
expiry_time = start_time + expiry_duration.to_i
end
def expiry_duration
expiry_time - created_at
end
end
What do you think?
use new_record?
, or use :on => :create
to call a different funciton
精彩评论