Search code examples
ruby-on-railscontrollercrudbefore-filter

Checking an attribute is true before executing a CRUD action


Before any of my article controller crud actions can run (excluding index), i want to make sure that the article's active field is true. I thought about doing this in a before_filter, but at that point @article has not been set, any ideas please?

Thanks


Solution

  • You could set the article in a helper method and remove some code duplication while you're at it.

    class .. < ApplicationController
    
      helper_method :current_article
    
      def index
        # your code etc..
      end
    
      private
    
      def current_article
        @article ||= Article.find(params[:id], :conditions => { :active => true }) || 
                     raise(ActiveRecord::RecordNotFound)
      end
    
    end
    

    Basically you can now call current_article in your show, edit (etc) actions and views instead of @article.