0

I have a Citation class and I want each Citation to have many Resources. A resource can be a LocalFile, Link (and maybe something like a dropbox file). Resources will share most functionality and columns. I want to use single table inheritance in the following manner.

class Resource < ActiveRecord::Base
  belongs_to :citation
  acts_as_list :scope => :citation
end

class LocalFile < Resource
end

class Link < Resource
end

class Citation < ActiveRecord::Base
  has_many :resources, class_name: "Resource"
end

I want to be able to get a collection of resources with code something like

cites = mycite.citations

and have each object in cites have the appropriate type (LocalFile, Link etc..). Will this work? Strangely despite searching extensively I haven't been able to find an answer to this simple question.

Also, will the methods added by acts_as_list work appropriately when called on objects on the various subtypes, i.e., give move them up or down in the list on all resources for a single citation

Alternatively, is there a better way to do this? I want to have the Citation class have a collection of resources of multiple subtypes. Conceptually, each resource type is capable of representing the same content just accessed in different ways.

Peter Gerdes
  • 2,288
  • 1
  • 20
  • 28

1 Answers1

0

STI should be considered when dealing with model classes that share much of the same functionality and data fields, but you as the developer may want more granular control over extending or adding to each class individually. Rather than duplicate the code over and over for multiple tables (and not being DRY) or forego the flexibility of adding idiosyncratic functionality or methods, STI permits you to use keep your data in a single table while writing specialized functionality.

to implement STI:-

  1. Create the base class
  2. Along with your needed attributes, add a :type attribute as a string to the base class
  3. Create any necessary descendant classes

Drawbacks of STI

STI isn’t always the best design choice for your schema. If sub-classes that you intend to use for STI have many different data fields, then including them all in the same table would result in a lot of null values and make it difficult to scale over time. In this case, you may end up with so much code in your model sub-classes that the shared functionality between sub-classes is minimal and warrants separate tables. Also, as I mentioned above, STI shouldn’t be used just because two object types have similar attributes - both airplanes and bicycles have wheels, but it probalby doesn’t make sense to group them into the same table, given that intuitively, they’re different objects that will have vastly different functionality and data fields in an application.

HOPE IT HELPS :)

Milind
  • 4,535
  • 2
  • 26
  • 58