I followed the post http://techspry.com/ruby_and_rails/multiple-table-inheritance-in-rails-3/ to implement the multiple table inheritance with Rail 4. I have three models: user, applicant and tutor. Here is my code:
class User < ActiveRecord::Base
belongs_to :student, :polymorphic => true
end
class Tutor < ActiveRecord::Base
acts_as_student
end
class Applicant < ActiveRecord::Base
acts_as_student
end
# in the /lib/student_module.rb
module Student
def acts_as_student
include InstanceMethods
has_one :user, :as => :student, :autosave => true, :dependent => :destroy
alias_method_chain :user, :build
user_attributes = User.content_columns.map(&:name) #<-- gives access to all columns of Business
# define the attribute accessor method
def student_attr_accessor(*attribute_array)
attribute_array.each do |att|
define_method(att) do
user.send(att)
end
define_method("#{att}=") do |val|
user.send("#{att}=",val)
end
end
end
student_attr_accessor *user_attributes #<- delegating the attributes
end
module InstanceMethods
def user_with_build
user_without_build || build_user
end
end
end
The User Table has username, email attributes.The Tutor table has first_name,last_name,intro,program,entry_year attributes. In the rails console, I got
tutor = Tutor.new => #<Tutor id: nil, first_name: nil, last_name: nil, intro: nil, created_at: nil, updated_at: nil, entry_year: nil, program: nil>
tutor.username
=> ActiveRecord::UnknownAttributeError: unknown attribute: student_id
I found the error was from the student_attr_accessor method. How should I fix it? Thanks!