문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top