small medium large xlarge

Generic-user-small
21 Oct 2008, 19:00
Christoph Ossner (9 posts)

Hi,

i want to explain what i want to do with the following example: I want to model students and employees. With EER i would use partitioning to do that and create a model persons, to carry the attributes both, students and emploees, have in common. How do i model that? Well my guess was the follwing:

class Person < ActiveRecord::Base
  has_many :students
  has_many :employees
end

class Employee < ActiveRecord::Base
  belongs_to :persons
end

class Student < ActiveRecord::Base
  belongs_to :persons
end

Now i had to pass the attributes out of params[:xy] in view/students/new to a call of Person.new() …quite verbous, and since i remember i had problems to validate the fields that belong to Person.

Maybe i should do something like the following:

class Person < ActiveRecord::Base
  
end

class Employee < Person
 
end

class Student < Person
  
end

Sad wise there are no examples for inheritance among models in the book.

Hope somehone has suggestions.

Generic-user-small
22 Oct 2008, 02:33
James West (104 posts)

I’m not entirely sure that would work. I’m still trying to get my head round this sort of problem though so don’t take this as gospel. I think that this is where rails lets itself down somewhat due to it’s wrapping active record classes round database tables.

In another environment I would have an abstract base class of person and the employee and studemt classes would inherit from this. this is indeed what it looks like you are trying to do here BUT from my little understanding of the way activerecord works the base class (person) in this instance would map to a person table and then all derived classes would also map to the same table as they have inherited the table from the base class.

I think that doing things that way is do-able but not ideal and would need you to re-think the database design somewhat. i.e. having a person type that can be set to either employee or student in the specific relevant model class.

I hope this makes sense and I stand to be corrected.

Is there another way? There will undoubtedly be another way that will enable you to closer mapyour database in this way but I really don’t know what that way would be and for me to suggest anything would be a case of the blind leading the blind.

It might be worth taking a look at helpers as an option for views and it may be that you could have a module that you could mix in with your controllers in order to share code wthout the need to inherit.

I only got that idea coz I’ve just been reading page 686 about modules and it seems like it fits

Generic-user-small
24 Oct 2008, 16:28
Christoph Ossner (9 posts)

mea culpa, mea maxima culpa…

for those who were as sleepy as me, while reading 18.4. There is the answer.

You must be logged in to comment