rails中的sti和has_many

时间:2010-06-25 08:19:23

标签: ruby-on-rails

class Register < User
end

class Admin < User
end

class Project < ActiveRecord::Base
  has_many :admin, :class => 'User', :conditions => "type = 'admin'"
  has_many :registers, :class => 'User', :conditions => "type = 'registers'"
end

这里的问题是,当我使用项目来has_many创建一个寄存器或管理员时,它不会将填充对象类自动化为类型字段。

像这样:project.admins.new

如何解决这个问题?

1 个答案:

答案 0 :(得分:14)

您应该能够直接指定has_many关系,而无需告诉Rails该类是User。像这样:

class User < ActiveRecord::Base
  belongs_to :project
end

class Register < User    
end

class Admin < User
end

class Project < ActiveRecord::Base
  has_many :admins
  has_many :registers

  def make_new_admin
    ad = admins.create(:name => "Bob")
    # ad.type => "Admin"
  end
end