Rails 3 Disable model not delete
I have several models that I want the user to "disable" it vs destroying it. These models have a disable boolean. trying to make this work.
currently in application_controller.rb
helper_method :disable
def disable(model)
@model = "#{model}".find(params[:id])
@model.update_attribute(:disable => t开发者_高级运维rue)
flash[:notice] = "Successfully disabled #{model}."
redirect_to company_ + "#{model}".pluralized + _url(current_company)
end
Do I have to create a new path in routes for each one I want to use this function? Would be ideal, if I can do something similar like the destroy method.
I would probably extend ActiveRecord with a disable method so that you can call @model.disable() just like you would @model.destroy(). That way you can leave all the default routes as is and just change the destroy action in your controller to try disable() instead of destroy().
Perhaps like this:
module MyDisableModule
def self.included(recipient)
recipient.class_eval do
include ModelInstanceMethods
end
end
# Instance Methods
module ModelInstanceMethods
#Here is the disable()
def disable
if self.attributes.include?(:disabled)
self.update_attributes(:disabled => true)
else
#return false if model does not have disabled attribute
false
end
end
end
end
#This is where your module is being included into ActiveRecord
if Object.const_defined?("ActiveRecord")
ActiveRecord::Base.send(:include, MyDisableModule)
end
And then in your controller:
def destroy
@model = Model.find(params[:id])
if @model.disable #instead of @model.destroy
flash[:notice] = "Successfully disabled #{@model.name}."
redirect_to #wherever
else
flash[:notice] = "Failed to disable #{@model.name}."
render :action => :show
end
end
Note that in this example, disabled is the attribute and disable is the method that makes a model disabled.
精彩评论