Describing a "replaces" relationship within the same model

Hi!

I would like to describe the relationships between two objects of a
model, where one of the objects replaces the other. I want to be able
to tell if one object has been replaced and, if so, by what object; and
vice versa what object an object replaces, if any. My idea was the
following:

create_table :events do |t|
t.column :replacement_id, :integer
t.column :description, :text, :null => false
end

create_table :replacements, {:id => false} do |t|
t.column :original_id, :integer, :null => false
t.column :new_id, :integer, :null => false
t.column :date, :date, :null => false
end

Is this a reasonable model and, if so, how should I link Event and
Replacement together?

My idea for the above was: An Event can belong to a Replacement and a
Replacement has an original Event and a new Event. One can thus tell if
an Event replaces or is replaced by another Event by looking at what
member of a Replacement an Event belongs to, i.e., if it is equal to
Replacement#original or Replacement#new. I also want to know the date
when the replacement was made.

Any suggestions are welcome.

nikolai

Nikolai W. wrote:

create_table :replacements, {:id => false} do |t|

Hm, I guess doing :id => false here isn’t right, so it should be

create_table :replacements do |t|

After realizing this the set up becomes the following:

create_table :events do |t|
t.column :replacement_id, :integer
t.column :description, :text, :null => false
end

create_table :replacements do |t|
t.column :original_id, :integer, :null => false
t.column :new_id, :integer, :null => false
t.column :date, :date, :null => false
end

And the models will be:

class Event < ActiveRecord::Base
belongs_to :replacement
end

class Replacement < ActiveRecord::Base
belongs_to :original,
:class_name => “Event”
:foreign_key => “original_id”
belongs_to :new,
:class_name => “Event”
:foreign_key => “new_id”
end

Does that seem reasonable?

I guess what confused me is that I always seem to read “belongs_to” as
“belongs to”, which makes sense for Event, instead of “references”,
which makes sense for Replacement, as is sometimes what you’re trying to
achieve.

nikolai

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs