Search code examples
ruby-on-railsruby-on-rails-4inheritancedevisesti

Should I use new or edit action on model that inherits from other model


I have the following models:

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

class Teacher < User 
end

class Student < User 
end

Users login in through a devise form that creates a user. I want to have two kinds of profiles like teacher and student though and they can be both at the same time as well.

So when I go to create a new Teacher I am just going to teachers/id/edit form and updating the teacher that inherits from user. Should I do this or can I go to teacher/new ? and create a teacher from there when I have my models inherit like I do?


Solution

  • Don't use inheritance here. Create separate TeacherProfile and StudentProfile tables, and make one-to-one associations:

    class TeacherProfile
      belongs_to :user
    end
    
    class StudentProfile
      belongs_to :user
    end
    
    class TeacherProfile
      has_one :teacher_profile
      has_one :user_profile
    end
    

    Then just follow the standard protocol. Go straight to edit, check if the profiles exists, and create it if it doesn't, something like this:

    def edit
      @profile = TeacherProfiler.where(user: current_user).first_or_create
    end