我真的不知道如何更好地表达这个问题,但这里有:
假设我有两个型号
class Record < ActiveRecord::Base
has_many :roles, :dependent => :destroy
end
class Role < ActiveRecord::Base
belongs_to :record
end
我想要一种方法来确保每次创建新记录实例时,系统会自动为该记录创建2个新角色。
每个role
都会有name
,record_id
,Boolean called edit
和Boolean called review
。
所以如果我创建一个名为record
的{{1}}并且它有一个ID Hello
,那么系统应该同时创建这两个新角色:
角色1:1
,name: Hello edit
,record_id: 1
,edit: true
角色2:review: false
,name: Hello review
,record_id: 1
,edit: false
答案 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