Rails polymorphic associations

The first in a likely series of posts regarding polymorphic associations in Rails that will illustrate my hitherto lack of understanding about how they work and my (hopeful) development to being able to use them effectively in my current project.

I’m going to need reminders and reference points when I get deeper into the project and start to make progress. I don’t necessarily expect this to be of use use to anyone else.

First off, I’m using https://6ftdan.com/allyourdev/2015/02/10/rails-polymorphic-models/ as a reference; so far it’s working well for me.

Start with a new git branch in case things don’t work out.

$ git checkout -b polymorphic_activities

The activities table already includes activityable_type and activityable_id columns but I needed another migration to the table to do the half-baked ideas I had before/

The Commission model includes,

class Commission < ApplicationRecord
belongs_to :request
 belongs_to :commission_type
 has_many :activities, :as => :activityable, :dependent => :destroy

The Activity model includes

class Activity < ApplicationRecord
 validates :title, :presence => true, :uniqueness => true
 validates :activityable_id, :presence => true
 validates :activityable_type, :presence => true
 
 belongs_to :activityable, :polymorphic => true

And we can test this with the Rails console with something like,

2.3.3 :002 > commission = Commission.first
2.3.3 :005 > commission.activities.build(title: "Background layers", details: "do some prep layers", number_of_slots: 3, min_slot_separation: 3).save

And we get an entry in the activities table with activityable_type set to Commission and activityable_id set to the id of the commission. Looks promising.

The main point at this stage is that I can bin the activity_commission, activity_other, activity_teaching tables (with ActivityCommission as the activityable_type) and just use Commission, etc. I’m beginning to see how this might work for all the other activity-based relationships I need to model. No need to abandon the project just yet.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s