Question

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

Was it helpful?

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.

OTHER TIPS

You just need to do 2 before_filter.

1 with load the article and the second one to check if field exist

  before_filter :load_article, :only => [:show, :edit, :update]
  before_filter :has_field, :only => [:show, :edit, :update]

  ...

  private

  def load_article
    @article = Article.find(params[:id])
  end

  def has_field
    unless @article.active
      redirect_to root_url
    end
  end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top