1

I have a Rails app in which the user can subscribe to addons, the list is dynamic and contains currently about 10 addons.

The list specifies which is on/off.

Each addon has a rather unique set of properties.


My current solution is that the application has 2 "parent" models and the one new model for each addon:

class AddonPrototype
  has_many :addons
end

class Addon
  belongs_to :addon_prototype
  belongs_to :user
end

class AddonAlpha
  belongs_to :addon
end

class AddonBeta
  belongs_to :addon
end

etc..
  1. The model AddonPrototype has one instance of each addon, with the default name as the only property.

  2. The model Addon with the properties enabled, custom_name. When the user is visiting the page with addons, a check is done to see whether the user has an Addon instance for each existing AddonPrototype, or else creating one on the fly.

  3. For each addon there is a unique model (e.g. AddonAlpha, AddonBeta etc), with the set of properties apt for each particular addon.

This design feels cumbersome, what could be a leaner setup?

Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232
  • What exactly are `AddonPrototype`, `AddonAlpha` and `AddonBeta`? – fivedigit Apr 16 '15 at 16:42
  • `AddonPrototype` is the grandparent, the canonical identifier of each unique addon, there would be about ten instances of it. `AddonAlpha` is the grandchild of one of the `AddonPrototype` instances and holds all settings for a particular user. – Fellow Stranger Apr 16 '15 at 16:47

1 Answers1

1

I'm probably missing out on some details, so take this post with a grain of salt.

Currently, the naming of the models seems to be a bit misleading. The AddonPrototype is an actual addon, whereas the Addon model represents the act of a user having installed an addon.

Here's the structure I would go for:

# app/models/user.rb
class User < ActiveRecord::Base
  has_many :installations
  has_many :addons, through: :installations
end

# app/models/addon.rb
class Addon < ActiveRecord::Base
  has_many :installations
  has_many :users, through: :installations
end

# app/models/installation.rb
class Installation < ActiveRecord::Base
  belongs_to :addon
  belongs_to :user
end

AddonPrototype has been renamed to Addon, and the old Addon model has been renamed to Installation (Subscription or something alike would also be a good name).

I would recommend against creating Installation records for each addon when a user visits the addons page. Just create these records when a user actually installs an addon. This keeps your code simpler and your database smaller.

fivedigit
  • 18,464
  • 6
  • 54
  • 58
  • Where would be the best place to store data unique to each Installation if each Addon has a different set of properties (let's say AddonA requires an external API key associated with it and AddonB just requires an email address)? – keshavdv May 06 '15 at 02:59