DRY up your Controllers with find_or_redirect

Do you do this:

class ModelsController < ApplicationController  
    before_filter :find_model
    def show
    end

    def destroy
      @model.destroy
    end

    private

    def find_model
      @model = Model.find_by_id(params[:id])
      unless @model
        redirect_to :action => :index
        flash[:error] = "Invalid model id"
        return false
      end
    end
  end

in every controller? Gets repetitive doesn't it?

How about this:

class ModelsController  
    find_or_redirect

    def show
    end

    def destroy
      @model.destroy
    end
  end

Now that's DRY!

gem install find_or_redirect  

More info on the find_or_redirect github page.

comments powered by Disqus