views:

34

answers:

2

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

+1  A: 

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
shingara
Thanks shingara, is that good practice/form?
pingu
+1  A: 

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.

vise
You might want to add a `before_filter` that checks the availability of the current_article also.
KandadaBoggu
I updated my code to raise an exception if the article is not found. The before_filter is not necessary as long as the method is being called at least once (which it is).
vise