Sergio Campamá
Sergio Campamá

Reputation: 746

Rails has_one/belongs_to conceptual debate

I am building an app where I have hierarchical modules, (bear with me with the absurd models, but the concept is the same) as in an Animal has a Tracker, and the Tracker has a Cellphone, each with its own serial_number... (Animal animal_id:10, Tracker serial_number:12, Cellphone imei:123456789123456)

What would be the acceptable way to define the relationships?

What I'm using now is this scheme:

Animal has_one Tracker, Tracker has_one Cellphone

Cellphone belongs_to Cellphoneable, Tracker belongs_to Trackable

(These are polymorphic relationships)

What I'm having trouble understanding is that I store the cellphoneable_id in the Cellphones table, but I'm starting to think that the relationship should reside in the Tracker table, and leave the Cellphone alone and let the upper layers relate down.

Upvotes: 0

Views: 181

Answers (1)

sled
sled

Reputation: 14625

Here's how I'd do it if:

  1. A tracker belongs to a single animal and a single cellphone
  2. If an animal can only have one tracker
  3. If a cellphone can be connected to multiple trackers and therefore multiple animals

Here's the code:

class Tracker < ActiveRecord::Base
  belongs_to :animal
  belongs_to :cellphone
end

class Animal < ActiveRecord::Base
  has_one  :tracker
  has_one  :cellphone, :through => :tracker
end

class Cellphone < ActiveRecord::Base
  has_many :trackers
  has_many :animals, :through => :trackers
end

Upvotes: 0

Related Questions