August 1, 2014 by Daniel P. Clark

Manual Polymorphic Creation in Rails

Finding documentation online to do this was pretty much a no go.  The answer I’ve provided here was grasped from hints given on many websites of what could be done but without anything I could really sink my teeth into.

What this code allows you to accomplish is to create a belongs_to/has_many relationship to something while maintaining only one of each kind.

If something will, or may, have more than one belongs_to relationship, then you should use polymorphic relationships. The available online documentation on that pretty much just covers the basics.  So I hope that this code outline will give you a deeper understanding and find success with polymorphic relationships with Rails from here on forward!

models/profile.rb

models/social.rb

controllers/profiles_controller.rb

I’ve shortened the actual file for just what’s relevant here. You will need any other parameters permitted for your use case. The rest can remain untouched.

controllers/application_controller.rb

This is where the magic will happen. It’s designed after .where(…).first_or_create but uses build instead so we don’t have to declare build for the socials object in the profile_controller.

And lastly the all important view:

(polymorphics most undocumented aspect.)

views/profiles/_form.html

 

The @social_list is defined in the profile_controller and is an array of label & kind pairs. So as each one gets passed through, the one_by_kind method we defined in the application_controller seeks for the first polymorphic child that has the right kind which we’ve named entry. If the database record isn’t found, it is then built. one_by_kind then hands back the object for us to write/update.

This maintains one view for both creating and updating polymorphic children. So it allows for a one of each kind within your profile and social relation.

Please comment, share, subscribe to my RSS Feed,and follow me on twitter @6ftdan!

God Bless! – Daniel P. Clark

#diy#howto#manual#one to many#polymorphic#rails#ruby on rails