Ruby on Rails Monday, November 28, 2011

kahou l. wrote in post #1033985:
> car1.wheels << wheel2
> car2.wheels << wheel2
>
> Note that car1 wheels STILL contains wheel2 when I reassign wheel2 to
> car2.
> I expect car1 doesn't have wheel2 anymore...
>
> I don't know why it doesn't get update automatically that car1 shouldn't
> contains wheel2 anymore. Can anybody help me to solve this problem?

The reason this happens is because Rails does not provide inter-model
change notification. Take the line:

car2.wheels << wheel2

Only car2 and wheel2 are involved in this statement. There is no change
notification system in Rails to send a message to car1 informing it that
anything changed. Therefore car1 only knows about the last state change
where it was actually involved. If you want car1 to "wake up" and update
it's internal state then you must do that yourself by either fetching it
again or forcing car1 to reload it's state from the database:

car1.reload

Using reload is typically not necessary in production code because the
next request usually refetches the objects involved anyway. But, it can
be useful in rare situations or when using the Rails console for exactly
the sort of experimenting that you're doing now.

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment