2011-03-01 54 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