2013-05-06 3 views
0

Я следил за сообщением http://techspry.com/ruby_and_rails/multiple-table-inheritance-in-rails-3/, чтобы реализовать множественное наследование таблицы с помощью Rail 4. У меня есть три модели: пользователь, претендент и наставник. Вот мой код:неизвестный атрибут errror при реализации рельсов множественное наследование таблицы

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 

Таблица Пользователь имеет имя, адрес электронной почты attributes.The таблицы Tutor имеет first_name, last_name, интро, программа, entry_year атрибутов. В консоли рельсы, я получил

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

Я обнаружил, что забыл объявить столбец внешнего ключа и столбца типа в пользовательской модели. Чтобы исправить это, просто выполните миграцию, например:

def change 
    add_column :users, :student_id,:integer 
    add_column :users, :student_type,:string 
    end 
Смежные вопросы