Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 is that when I use project to has_many to create a register or admin, it doesn't automatically fill the object class into the type filed, e.g., project.admins.new

How do I fix this?

like image 448
user285020 Avatar asked Jun 25 '10 08:06

user285020


1 Answers

The has_many relationships can be specified directly, without needing to tell Rails that the class is 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
like image 158
Chowlett Avatar answered Oct 23 '22 10:10

Chowlett