开发者

Rails MTI with polymorphism

开发者 https://www.devze.com 2023-03-11 12:04 出处:网络
Imagine the scenario: I have a class with different types of students. All students have similar attributes, but each type of student has also unique atributes. So I used MTI to keep the common attri

Imagine the scenario:

I have a class with different types of students. All students have similar attributes, but each type of student has also unique atributes. So I used MTI to keep the common attributes in the table students and the individual ones in their respective table, and polimorphism to abstract the student type when handling them from the class perspective. I followed this tutorial: http://techspry.com/ruby_and_rails/multiple-table-inheritance-in-rails-3/.

Fr开发者_JS百科om this, I got to these models:

class Clazz < ActiveRecord::Base
  has_many :students
end

class Student < ActiveRecord::Base
  belongs_to :stu, :polymorphic => true
  belongs_to :clazz
end

class Student1 < ActiveRecord::Base
  has_one :student, :as => :stu
end

class Student2 < ActiveRecord::Base
  has_one :student, :as => :stu
end

My problem comes when I want to instantiate a specific student (indirectly associated to the class through student). I can't do it from the class, because it doesn't have a connection to the specific students and when I try to instantiate it directly, it says it doesn't recognize the ':class' field.

Student1.new(:clazz => @clazz, ... [other atributes]...)

unknown attribute: :class

Can anyone give me a hint on how to accomplish this? Tks


Basically what @Aaron is trying to ask is does this work:

class Student < ...
  belongs_to :clazz
end

class Student1 < ...
  has_one :student, :as => :stu

  accepts_nested_attributes_for :stu
end

Student1.new(:stu => {:clazz => @clazz},...[other attributes])

ActiveRecord doesn't do you any favors by default when you need to initialize across trees of objects like this.


Check out the solution here: http://mediumexposure.com/multiple-table-inheritance-active-record/

which is similar to http://techspry.com/ruby_and_rails/multiple-table-inheritance-in-rails-3/.

but from my experience, the former is better. for one, it implements method_missing, which the latter doesn't do.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号