I have a problem. I want to know if it is possible to call a method
(in the controller of a class) from an action, a callback or something
in a related model.
e.g.
Model A “has many” Model B
But every time Model A is updated I need to execute a (custom)
controller method in Model B
Well, the example I used is a little simple for what I really need.
I have 4 models
Model A, Model B, Model C, and Model D
Everytime I update Model C, I have to update Model B
Everytime I update Model D, I have to update Model B
Everytime I update Model B, I have to update Model A, but this update
depends on “which” model has updated Model B. if Model C has updated
Model B I have to make some changes in Model A. But if Model D has
updated Model B I have to make differnts changes in Model A.
My problem is that I don’t know how can I recognize which model has
updated Model B to “switch” between actions to update Model A
depends on “which” model has updated Model B. if Model C has updated
Model B I have to make some changes in Model A. But if Model D has
updated Model B I have to make differnts changes in Model A.
I think the simplest way to do this is to have an after_save callback on
ModelC and ModelD.
Just call the method that will update ModelB and ModelA on the
callbacks.
Then in your model, you could do something like this:
after_save :update_model_a
def update_model_a
model_a = ModelA.find
model_a.foo = “bar” if updated_by_model = ModelC
model_a.foo = “rab” if updated_by_model = ModelD
end
These are just very broad ideas since I don’t know the specifics.
Hopefully
they will spark some ideas for you, but it should be possible to do this
in
a more “railsy” way than calling a controller action from a model
Well, the example I used is a little simple for what I really need.
I have 4 models
Model A, Model B, Model C, and Model D
Everytime I update Model C, I have to update Model B
Everytime I update Model D, I have to update Model B
Everytime I update Model B, I have to update Model A, but this update
depends on “which” model has updated Model B. if Model C has updated
Model B I have to make some changes in Model A. But if Model D has
updated Model B I have to make differnts changes in Model A.
My problem is that I don’t know how can I recognize which model has
updated Model B to “switch” between actions to update Model A
Sounds like what you need is Key Value Observing (KVO). Too bad I know
of nothing like that anywhere in Rails. Plus it probably doesn’t make
sense in a web application anyway.
On Wed, Aug 24, 2011 at 11:20 AM, Angelo C. [email protected]
wrote:
Everytime I update Model B, I have to update Model A, but this update
depends on “which” model has updated Model B. if Model C has updated
Model B I have to make some changes in Model A. But if Model D has
updated Model B I have to make differnts changes in Model A.
One Adam 12, code 7, Law of Demeter violation in progress