← Back to Upcase

Using polymorphism

(Charlieanna) #1

I have a Project model which has a setting for Android device and a setting for an Apple Device.
Android setting takes in an api_key wheres Apple Device takes in a password and a certificate.

Intially I had Project has_one Android_Setting and one Apple_Setting

But now I am trying to use polymorphism

class Setting < ActiveRecord::Base
  belongs_to :project
  belongs_to :device_setting,polymorphic: true

and Project has_many :settings.

Device_Setting_Type could be AppleSetting or AndroidSetting.

Now my question is can I get the AppleSetting from the project?

Currently I am using this


(Chris Toomey) #2

Hello Ankur,

It’s a little hard to answer without understanding where the device setting is used. In general with polymorphism you want to interact via a uniform interface. The code that is collaborating with your Setting class should not have to care if it is an AppleSetting or an AndroidSetting. This may be difficult since the two have such distinct configurations.

Here is a post on replacing conditional with polymorphism which might provide some clarity.