views:

48

answers:

2

Basically I have two chains of models, one holds 'predicted data' and one holds 'actual data'. I would like to copy all predicted data to actual when an actual is created.

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

This code doesn't work, any ideas? I'm trying to copy each Route and all its Runs from the given EffectiveDate into its parent Employee instance.

Update:

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)

Why am I getting this error?

A: 

This works:

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
jblaster
A: 

Have you tried deep_clonable from github? It's supposed to support rails3 - however, it is not working for me