Echotest
Echotest

Reputation: 129

Opposite direction of polymorphic association rails

I have an example in my app where I'm able to assign/access polymorphic association but am I not able to access the class back from the polymorphic association,

class EmailCampaignSubscription < ActiveRecord::Base
  belongs_to :subscribable, polymorphic: true
end

class Order < ActiveRecord::Base
  has_one :email_campaign_subscription, as: :subscribable
end

This works EmailCampaignSubscription.last.subscribable but this does not Order.last. email_campaign_subscription. Also this does not work :

EmailCampaignSubscription.last.subscribable.email_campaign_subscription

By does not work I mean it returns nil.

This works (returns the correct record):

EmailCampaignSubscription.where(subscribable_type: "Order", subscribable_id: Order.last.id)

I am using rails 4.2.11, why does this accessor back to email_campaign_subscription does not work and how can I fix the association definition to make it work?

Update:

I tried this :

has_one :email_campaign_subscription, class_name: 'EmailCampaignSubscription', as: :subscribable

Still got nil.

Upvotes: 2

Views: 191

Answers (1)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

You need to pass class_name option with polymorphic has_one

has_one :email_campaign_subscription, class_name: 'EmailCampaignSubscription', 
                                      as: :subscribable

Give it a try.

Upvotes: 1

Related Questions