lucas clemente
lucas clemente

Reputation: 6389

"Inherited" data in Rails

I have a datamodel, which I want to describe in Rails. There are many Entity, each one has_many :blobs, and each Blob belongs_to one Entity. Additionally, each Entity may belong_to a parent Entity. It should inherit all of the parent's Blobs. Is there any nice way of modeling this in Rails? Stated differently, is there a way of doing something like this:

# Beware, wrong code
class Entity < ActiveRecord::Base
  has_many :blobs
  has_many :blobs, :through => :parent, :source => :blobs
end

Or maybe a different idea on how to do this?

Upvotes: 0

Views: 60

Answers (1)

Rein Henrichs
Rein Henrichs

Reputation: 15605

Something very similar to this should work:

class Entity
  belongs_to :parent, :class_name => 'Entity', :foreign_key => 'parent_id'
  has_many :children, :class_name => 'Entity', :foreign_key => 'parent_id'
  has_many :direct_blobs, :class_name => 'Blob'
  has_many :inherited_blobs, :class_name => 'Blob', :through => :parent, :source => :direct_blobs

  def blobs
    direct_blobs + inherited_blobs
  end
end

Upvotes: 1

Related Questions