我按照帖子http://techspry.com/ruby_and_rails/multiple-table-inheritance-in-rails-3/实现了Rail 4的多表继承。我有三个模型:用户,申请人和导师。这是我的代码:
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
用户表具有用户名,电子邮件属性.Tutor表具有first_name,last_name,intro,program,entry_year属性。 在rails控制台中,我得到了
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
我发现错误来自student_attr_accessor方法。我该如何解决?谢谢!
答案 0 :(得分:0)
我发现我忘了在用户模型中声明外键列和类型列。要解决此问题,只需运行以下迁移:
def change
add_column :users, :student_id,:integer
add_column :users, :student_type,:string
end