如何通过has_many关系创建指定类型的对象?

时间:2013-10-24 21:14:57

标签: ruby-on-rails ruby activerecord

请考虑以下事项:

class Person < ActiveRecord::Base   
end

class Man < Person
end

class Woman < Person
end


class Society < ActiveRecord::Base
    has_many :person

    def addPeople
        people.create(:name => "bill")
        people.create(:name => "sue")
    end
end

如何定义此人的类型?例如,我想创建一个男人的账单,并作为一个女人起诉。这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:4)

按类

指定对象的类型
class Society < ActiveRecord::Base
  has_many :persons

  def add_people 
    self.persons << Man.create name: 'bill'
    self.persons << Woman.create name: 'sue'
  end
end