Just wondering if there's a simple way to restfully delete entries by updating a database field instead of dropping the entry from the database?
Specifically, I'd like to trigger "deleted=1" instead of "drop from 开发者_运维百科database" whenever a RESTful "delete" function can be run.
Any ideas appreciated...
There's no reason to do a bunch of work in the controllers when you can control everything in the model. Add a deleted_at column to your model, override the destroy() method, then set your default_scope to where(:deleted_at => nil).
Do all this, of course, only if you don't want to use acts_as_paranoid (github, rubygems).
class User < ActiveRecord::Base
acts_as_paranoid
end
I'm not an expert, but I'd probably create a destroy
method on the controller and implement the desired bevahior there.
I do this for stuff I don't want to destroy. Lots of apps do this for users, so they don't destroy the information but really disable the account.
rails g migration add_deleted_boolean_to_model
- add the code in Part 2 into the migration
- rake
db:migrate
- ad the code in Part 3 into the controller
Part 2 - In your migration file:
add_column :modle_name, :deleted, :boolean, :default => false
Then rake db:migrate
Part 3 - In your controller:
def destroy
@object = Model.find(params[:id)
@object.update_attribute(:deleted, true)
end
def index
@objects = Object.find(:all, :conditions => ['deleted=?', false])
end
def show
@object = Model.find(params[:id)
@object = nil if @object.deleted
flash[:notice] = "Sorry that was deleted; contact admin if you want it resated"
end
Keep in mind the find conditions are not rails3, maybe someone will edit that.
精彩评论