Composite Key Associations in Rails 3

I have 4 models in my rails app:

Class / Teacher / Student / Assignment

I need to have:

n * n relationship between classroom and teacher
n * n relationship between teacher and student

This is ok for these two relationships as I will create 2 migrations for has_and_belongs_to_many.

For the Assignments model, I need to associate it with the three previous models:

The assignment table should look like this: - id
- label
- classroom_id
- teacher_id
- pupil_id

Is the best approach to modeling this latter relationship?

class Assignment < ActiveRecord::Base
  belongs_to: classroom
  belongs_to: teacher
  belongs_to: pupil
end

class classroom < ActiveRecord::Base
  has_many: assignments
end

class teacher < ActiveRecord::Base
  has_many: assignments
end

class pupils < ActiveRecord::Base
  has_many: assignments
end

      

+3


source to share


1 answer


Consider a polymorphic association http://guides.rubyonrails.org/association_basics.html#polymorphic-associations



class Assignment < ActiveRecord::Base
  belongs_to: assignable, :polymorphic => true
end

class Classroom < ActiveRecord::Base
  has_many :assignment, :as => :assignable
end

      

0


source







All Articles