基本上我有两个模型链,一个包含'预测数据',另一个包含'实际数据'。我想在创建实际数据时将所有预测数据复制到实际数据。
def init_data
employees = Employee.all
employees.each do |e|
t = e.template
ed = t.effective_dates.first
if ed and !e.routes
routes = ed.routes.collect do |r|
runs = r.runs.collect { |run| run.clone() }
r.route_type.runs.map do |run|
runs.push run.clone()
end
route = r.clone()
route.effective_date_id = nil
route.actual_id = self.id
route.employee_id = e.id
route.runs = runs
route.save
end
end
e.save
end
self.save
end
这段代码不起作用,有什么想法吗?我正在尝试将每个Route及其所有运行从给定的EffectiveDate复制到其父Employee实例中。
更新
ree-1.8.7-2010.02 > employees.each do |e|
ree-1.8.7-2010.02 > routes = e.template.effective_dates.first.routes.map do |route|
ree-1.8.7-2010.02 > new_route = route.clone
ree-1.8.7-2010.02 ?> new_route.runs << route.runs.map(&:clone)
ree-1.8.7-2010.02 ?> new_route
ree-1.8.7-2010.02 ?> end
ree-1.8.7-2010.02 ?> e.routes = routes
ree-1.8.7-2010.02 ?> e.save
ree-1.8.7-2010.02 ?> end
ActiveRecord::AssociationTypeMismatch: Route(#2176300240) expected, got Route(#2177787760)
为什么我收到此错误?
答案 0 :(得分:0)
这有效:
def init_data
employees = Employee.all
employees.each do |e|
ed = e.template.effective_dates.first
if ed
ed.routes.map do |route|
route_attrs = route.attributes
route_attrs[:effective_date_id] = nil
route_attrs[:actual_id] = self.id
new_route = Route.new(route_attrs)
new_runs = route.runs.map do |run|
Run.new(run.attributes)
end
new_route.runs = new_runs
e.routes << new_route
e.save
end
end
end
end
答案 1 :(得分:0)
您是否尝试过github的deep_clonable?它应该支持rails3 - 但是,它不适用于我