Sti and has_many in 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

the problem here is that when I use project to has_many create a register or administrator, it does not automate filling the object class into filed type.

like this: project.admins.new.

How to solve this problem?

+6
source share
1 answer

You should be able to directly specify has_many relationships without telling Rails that this class is User. For instance:

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
+14
source

All Articles