Search code examples
rubyroutessingle-table-inheritanceruby-on-rails-3formhelper

Form helpers in case of Single Table Inheritance


I have to implemene Single Table Inheritance for a class Person who can be of type Teacher, Student,Outsider.

class Person < ActiveRecord::Base

end


class Teacher < Person

end

class Student < Person

end

class Outsider < Person

end

What changes do I need to make in the routes and the forms while register a new user. I have a column(string) "type" in the people table which can be implemented as a dropdown in the form to register a new user. Is there anything else that I need to do in the form so the user is registered as a particular type of Person? Do I need to make any changes in the routes too?


Solution

  • Except adding a dropdown list of type selection in the form, there's nothing more to do. You can create a user in the normal way, like:

    @user = Person.new params[:user]
    

    But the type attribute could not be mass assigned, so you have to assign it separately.

    @user.type = sanitize_user_type params[:user][:type]
    

    The method sanitize_user_type is used to validate user input value.

    The route for creating new user doesn't need to change. Whether other routes need to change or not depend on your requirement. Actually you can add the routes for Teacher, Student, Outsider and relative controllers, so that you can build restful urls.