在创建不同的模型时自动生成模型的实例?

时间:2011-03-02 22:02:02

标签: ruby-on-rails

我真的不知道如何更好地表达这个问题,但这里有:

假设我有两个型号

class Record < ActiveRecord::Base
  has_many :roles, :dependent => :destroy
end

class Role < ActiveRecord::Base
  belongs_to :record 
end

我想要一种方法来确保每次创建新记录实例时,系统会自动为该记录创建2个新角色。

每个role都会有namerecord_idBoolean called editBoolean called review

所以如果我创建一个名为record的{​​{1}}并且它有一个ID Hello,那么系统应该同时创建这两个新角色:

角色1:1name: Hello editrecord_id: 1edit: true

角色2:review: falsename: Hello reviewrecord_id: 1edit: false

2 个答案:

答案 0 :(得分:2)

ActiveRecord回拨救援:

class Record < ActiveRecord::Base
  after_create :create_roles

  def create_roles
    Role.create :name => "Hello edit", :record_id => self.id, :edit => true, :review => false
    Role.create :name => "Hello review", :record_id => self.id, :edit => false, :review => true
  end
end

答案 1 :(得分:1)

试试这个:

class Record < ActiveRecord::Base
  has_many :roles
  after_create :add_roles

  def add_roles
    roles.create [
      {:name => "Hello edit", :edit => true, :review => false},
      {:name => "Hello review", :edit => false, :review => true}]
  end
end