Association type cast or: Building instances of a given class on polymorphic/STI collections « mediapeers development blog
Lee Iverson in leei's Channel
A snippet to allow building of subclasses of an association in an STI hierarchy.
Captured on 09 Jul 2010 from mediapeers.wordpress.com
In quite some cases you want to
build items on a rails collection instead of appending them, especially when the parent object is already stored in the database and you do not want the new item being saved automatically. However, this approach does not work on polymorphic collections as you cannot specify the class of the item being built in the build call. You can find some solutions on the net interpreting the type attribute, however I consider this unsafe because attributes tend to be taken directly from the params hash (actually, type attributes are filtered by default on mass assignments which does certainly make sense). The following code snippet adds a build_a method to has_many collections which allows you to sayResponses
- Order By
- First Post First
- Last Post First
Please Login to respond