开发者

single-table inheritance (STI) and has_many in rails doesn't automatically fill the object class into the type filled

class Register < User
end

class Admin < User
end

class Project < ActiveRecord::B开发者_Python百科ase
  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?


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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜