I have a 'chunk of code' that performs calculations on data and updates some tables based on those calculations.
I'd like t开发者_JAVA百科o be able to reference that chunk of code from multiple locations, something like this:
# from controller or model
def ...
...
run `chunk of code`
...
end
This is an inordinately simple question - where would chunk of code
go and how would I get Rails to run it from controller/model?
Calculations or table updates belongs to a model, so what about defining some new class method in your model, e.g.
def self.calculate
...
chunk of code
...
end
it can be then called from both model and controller
I managed it by doing:
def calculate
chunk of code
end
Then to call it from the model/controller:
def some_other_action
...
@record.calculate (or self.calculate in model)
...
end
精彩评论