2014-04-30 80 views
1

的容器,我有一个父类个人和子类学生教授在我的Rails应用程序。传递一个孩子父类型

继承是通过名为'acts_as_relation'的gem来处理的,该gem模拟多个表继承。

此外,我有一个行动,其中一个学生实例附加到个人列表。通常我本来期望这要经过没有任何问题,但我得到这个错误:

ActiveRecord::AssociationTypeMismatch: Individual(#70220161296060) expected, got Student(#70220161349360) 

这里是我的模型一览:

class Individual < ActiveRecord::Base 
    acts_as_superclass 
end 

class Student < ActiveRecord::Base 
     acts_as :individual 
end 

class Professor < ActiveRecord::Base 
     acts_as :individual 
end 

回答

0

我没有用这种宝石,但能给你一些帮助,here's what I've foundthis

They both mention that you're calling an object through your relation, which will have confusion over polymorphism or similar. The two posts could not fix the issue, and I presume that is because they could find the correct object for their relationship


在此进一步看,我发现this tutorial on the gem homepage

acts_as_relation uses a polymorphic has_one association to simulate multiple-table inheritance. For the e-commerce example you would declare the product as a supermodel and all types of it as acts_as :product (if you prefer you can use their aliases is_a and is_a_superclass)

class Product < ActiveRecord::Base 
    acts_as_superclass 
end 

class Pen < ActiveRecord::Base 
    acts_as :product 
end 

class Book < ActiveRecord::Base 
    acts_as :product 
end 

To make this work, you need to declare both a foreign key column and a type column in the model that declares superclass. To do this you can set :as_relation_superclass option to true on products create_table (or pass it name of the association):

create_table :products, :as_relation_superclass => true do |t| 
    # ... 
end 

Or declare them as you do on a polymorphic belongs_to association, it this case you must pass name to acts_as in :as option:

change_table :products do |t| 
    t.integer :producible_id 
    t.string :producible_type 
end 

class Pen < ActiveRecord::Base 
    acts_as :product, :as => :producible 
end 

class Book < ActiveRecord::Base 
    acts_as :product, :as => :producible 
end 

你确定你有你的数据表设置是否正确?

+0

感谢您的回复。我几乎可以肯定,数据库没有问题。设置好gem之后,我使用rails控制台检查了功能,并将数据插入到数据库中。根据文档,很明显,Book和Pen都在扩展ActiveRecord :: Base,所以这可能是这里要做的。宝石本身工作正常,直到我想要一个孩子在父母类型的集合... – mdoust

+0

hmmmm - 我希望我可以帮忙,但我没有任何宝石抱歉的经验! –

0

我在我的项目中解决这个问题的方法是使用instance_ofsome_class.individuals << student_instance.individual

这里的事情不是真正的MTI,因此您的个人收藏只能接受个人实例。如果您拨打some_student_instance.individualsome_professor_instance.individual,您会得到与您的特定实例相关的单个实例。 然后,使用该集合,如果你想要一个学生或教授,你所需要做的就是致电individual_in_collection.specific。例如:

p = Professor.create 
a_model.individuals << p.individual 
puts "#{a_model.individuals.first.class.name}" 
=> Individual 
puts "#{a_model.individuals.first.specific.class.name}" 
=> Professor 
+0

感谢您的回复。这确实可以解决问题,但我不想对教授,学生或任何其他未来子孙打电话给“个人”。 – mdoust

相关问题