Can't save a cloned record
I am trying to provide undo functionality after a record has been deleted. To do this, before I delete the record I clone it and put it in the session like so:
session[:undo] ||= []
session[:undo] << record.clone
however when I later do
rec = session[:undo][-1]
rec.save!
The record is not saved. The server console output says
(0.2ms) BEGIN
[paperclip] Saving attachments.
(0.2ms) COMMIT
which makes me think it is s开发者_C百科aved, but its not in the db. I am very confused. Any ideas?
A more stable way of doing this is to have an "active" boolean flag in the database that defaults to true. When you delete a record, just change that flag to false. To undo you just change it back to true.
# models/attachment.rb
class Attachment < ActiveRecord::Base
default_scope where(:active => true)
def self.include_inactive
unscoped
end
end
# in your migration
def self.up
change_table :attachments do |t|
t.boolean :active, :default => true, :null => false
end
add_index :attachments, :active
end
The self.include_inactive
method is really just for clarity. It is really just an alias of unscoped
, which will reset the default_scope
that is ignoring deleted records. If you want to, for example, show all records in an admin dashboard, you can call Attachment.include_inactive
.
Also note the index on the active
column. Since most queries will include a where 'active' = 1
it is smart to ensure your database has this information easily accessible.
精彩评论