Example:
Room has_and_belongs_to_many_with_deferred_save PeopleLets say you want to validate the room.people collection and prevent the user from adding more people to the room than will fit. If they do try to add more people than will fit, you want to display a nice error message on the page and let them try again...
This isn't possible using the standard has_and_belongs_to_many due to these two problems:
When I do the assignment to my collection (room.people = whatever), it immediately saves it in my join table (people_rooms) rather than waiting until I call room.save. You can "validate" using habtm's :before_add option ... but it any errors added there end up being ignored/lost. The only way to abort the save from a before_add seems to be to raise an exception... We don't want to raise an exception when the user violates my validation. We want validation of the people collection to be handled the same as any other field in the Room model: We want it to simply add an error to the Room model's error array which we can than display on the form with the other input errors.
has_and_belongs_to_many_with_deferred_save solves this problem by overriding the setter method for your collection (people=), causing it to store the new members in a temporary variable (unsaved_people rather than saving it immediately.
You can then validate the unsaved collection as you would any other attribute, adding to self.errors if something is invalid about the collection (too many members, etc.).
The unsaved collection is automatically saved when you call save on the model.
See http://github.com/TylerRick/habtm-with-deferred-save for more info.
30 Day Summary Apr 17 2013 — May 17 2013
|
12 Month Summary May 17 2012 — May 17 2013
|
Copyright
©
2013
Black Duck Software, Inc.
and its contributors, Some Rights Reserved. Unless otherwise marked, this work is licensed under a
Creative Commons Attribution 3.0 Unported License
. Ohloh
®
and the Ohloh logo are trademarks of
Black Duck Software, Inc.
in the United States and/or other jurisdictions. All other trademarks are the property of their respective holders.