私は投稿http://techspry.com/ruby_and_rails/multiple-table-inheritance-in-rails-3/に従って、 Rail 4 で複数テーブルの継承を実装しました。ユーザー、申請者、チューターの 3 つのモデルがあります。これが私のコードです:
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
ユーザー テーブルには、ユーザー名、電子メールの属性があります。チューター テーブルには、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 メソッドによるものであることがわかりました。どうすれば直せますか?ありがとう!