Question

I have a Student, Teacher, and University model. A Teacher has_many Universities and a Student has_one University.

Currently there is no Teacher or Student model but a single model User. In this way what would be relation between User and University? And what would be the correct schema?

Était-ce utile?

La solution

Firstly,you are lot confused with the associations.It is university has_many teachers not Teacher has_many Universities and also it is not Student has_one University,it is student belongs_to university.

And your point of giving only one model as User instead of having two models(teacher and Student) should be given like this

class University < ActiveRecord::Base

has_many :teachers, :class_name => "User"
has_many :students, :class_name => "User"

end

class User < ActiveRecord::Base

belongs_to :university

end

And I would recommend to read these Guides before going any further with associations.

Hope it helps!

Update

Well,in that point,you can do like this

class University < ActiveRecord::Base

    belongs_to :teacher, :class_name => "User",:foreign_key => 'user_id'
    has_many :students, :class_name => "User"

end

class User < ActiveRecord::Base

   has_many :universities

 end

Autres conseils

I believe you are looking for something called single table inheritance. Check out this article: http://www.alexreisner.com/code/single-table-inheritance-in-rails

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top