Association type cast or: Building instances of a given class on polymorphic/STI collections « mediapeers development blog

Association type cast or: Building instances of a given class on polymorphic/STI collections « mediapeers development blog
Lee Iverson

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 say

Responses

Please Login to respond

Get Gleanr!

What is Gleanr?

Gleanr is the networking engine for digital-age professionals. Get impact (& income!) in the information streams you care about.

How does it work?

Your custom Gleanr channels automate information flow relevant to you. All you do is "click" - we do the rest (instant capture, indexing, and networking).

What is the value?

Gleanr is the only web service where professionals can manage and monetize their expertise.

Is this more web 2.0?

Yes, but for work. Now you can capitalize on your unique ability to filter and enrich professional information streams.

Show me!

Explore the public parts of professional information streams here, or take the Gleanr Tour.

Sign me up!