What's a good construct for an intermediate triple relation model?

I'm new to Rails and don't understand all the possibilities with associations. Here's my problem:

I have a couple of models like apple and lemon. Then there is a model relation that contains triples of relations:

theme | attitude | an object

apple | sweeter than | lemon

The migration for the 'relationship' is:

create_table :relations do |t|
  t.references :subject,  :polymorphic => true
  t.string     :relation
  t.references :object,   :polymorphic => true
  t.timestamps    
end

      

this should store relationships like

subject_id = 1

subject_type = apple

ratio = sweeter than

object_id = 2

object_type = lemon

I actually have no more than two models, so I thought that I need to make the object model and object agnostic using the polymorphic variant.

How would you establish associations in the apple, lemon, and relationship model classes? Does the design of relationship tables look good?

Thank you very much for your help!

for -Alex-

0


a source to share


2 answers


Give the described db schema, it seems like it should be pretty simple:

class Relation < ActiveRecord::Base
  belongs_to :object, :polymorphic => true
  belongs_to :subject, :polymorphic => true
end

      



And your other classes will look like this:

class Apple < ActiveRecord::Base
  has_many :object_relations, :class_name => 'Relation', :as => :object
  has_many :subject_relations, :class_name => 'Relation', :as => :subject
end

class Orange < ActiveRecord::Base
  has_many :object_relations, :class_name => 'Relation', :as => :object
  has_many :subject_relations, :class_name => 'Relation', :as => :subject
end

      

+1


a source


Polymorphic IS PAIN:

If you don't need it, use somethimng as SingleTableInheritance:

class Fruit < ActiveRecord::Base
   has_many :relations
   has_many :related_objects, :through => :relation, :class_name => 'Fruit'
   has_many :relating_subjects, :through => :relation, :class_name => 'Relation'
end
class Relation < ActiveRecord::Base
   belongs_to :object, :class => 'Fruit'
   belongs_to :subject, , :class => 'Fruit'
   validate_presence_of :object_id
   validate_presence_of :subject_id
   validate_presence_of :relation
end

      



And then something like:

class Apple < Fruit
   ...
end

      

I hope this helps (I have not tested this code)

0


a source







All Articles