I’m in rails 3.0 and I’m working on a “project management” app. I’d like to duplicate an Item, which in my case is the “project”, and at the same time, duplicate all tasks that belong to that item.
I stuffed my Item model with code I found here: http://www.redmine.org/projects/redmine/repository/revisions/2704/diff/trunk/app/models/project.rb, which seems to do what I want, but I can’t make it work for me.
I’d like any help you can offer–general or specific! thanks!
class Task < ActiveRecord::Base
belongs_to :department
belongs_to :item
belongs_to :customer
end
class Item < ActiveRecord::Base
belongs_to :customer
has_many :tasks
def copy(item)
item = item.is_a?(Item) ? item : Item.find(item)
Item.transaction do
# Tasks
item.tasks.each do |task|
new_task = Task.new
new_task.copy_from(task)
self.tasks << new_task
end
self.save
Hook.call_hook(:model_item_copy_before_save, :source_item => item, :destination_item => self)
end
end
def self.copy_from(item)
begin
item = item.is_a?(Item) ? item : Item.find(item)
if item
# clear unique attributes
attributes = item.attributes.dup.except('id')
copy = Item.new(attributes)
copy.enabled_modules = item.enabled_modules
copy.trackers = item.trackers
copy.custom_values = item.custom_values.collect {|v| v.clone}
return copy
else
return nil
end
rescue ActiveRecord::RecordNotFound
return nil
end
end
Another thing–what is the Hook.call_hook…? I can’t find any references to that on the web
Look into ActiveResource::Base#clone.
It should probably work something like:
EDIT:
In the context of your model you could just have:
Then in your controller: