2011-03-01 51 views
2

我有几个模型,我希望用户“禁用”它与摧毁它。这些模型具有禁用布尔值。试图做这项工作。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 

我必须创建为每一个我想要使用此功能路由的新路径? 会是理想的,如果我可以做类似的销毁方法。

回答

5

我可能会用禁用方法扩展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 

注意,在这个例子中,残疾人是属性和禁用是使禁用的模型的方法。

+0

哇,高于我的方式。首先是这两个不同的文件或1?我问,因为我看到ModelInstanceMethods的额外结束。想象一下,我可以将它添加到我的/ lib目录并且只需调用include就可以了? – pcasa 2011-03-01 16:11:46

+0

不,它可以全部放在lib中的同一个文件中,除了正如我所说的在你的控制器中销毁。但是如果你觉得它很复杂或者只是想在第一时间尝试一下,那么你可以使用禁用方法,并手动将它放入你想要先尝试的模型中。 – DanneManne 2011-03-01 16:49:15

+0

尝试,但似乎没有工作。添加了Lib文件(完全按照上面的测试版发布),但仍然无法禁用? – pcasa 2011-03-01 20:47:00