Rails 3禁用模型不删除

时间:2011-03-01 15:12:05

标签: ruby-on-rails ruby-on-rails-3

我有几个模型,我希望用户“禁用”它并销毁它。这些模型具有禁用布尔值。试图让这项工作。

目前在application_controller.rb

helper_method:禁用

def disable(model)
 @model = "#{model}".find(params[:id])
 @model.update_attribute(:disable => true)
 flash[:notice] = "Successfully disabled #{model}."
 redirect_to company_ + "#{model}".pluralized + _url(current_company)
end

我是否必须在每个我想使用此功能的路线中创建新路径? 如果我可以像破坏方法那样做类似的东西,那将是理想的。

1 个答案:

答案 0 :(得分:5)

我可能会使用disable方法扩展ActiveRecord,这样就可以像@ model.destroy()一样调用@ model.disable()。这样你就可以保留所有默认路由,只需更改控制器中的destroy动作,尝试使用disable()而不是destroy()。

也许是这样:

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

然后在你的控制器中:

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

请注意,在此示例中,disabled是属性,disable是禁用模型的方法。