2012-03-01 9 views
0

私はカテゴリーコントローラを持っていると私は出力にホームページ内のすべてのカテゴリをしたいが、_menu.html.erbレイアウトで、私はこのエラーメッセージがあります。Railsのはnilオブジェクトエラー

You have a nil object when you didn't expect it! 
You might have expected an instance of Array. 
The error occurred while evaluating nil.each 

は、私が管理者としてログインしてIすべてのカテゴリを追加、編集、削除、表示できます。

これは私のコードの一部です:

_menu.html.erb

<div class="menu"> 
    <% @categories.each do |category| %> 
    <li> 
     <%= link_to category.title, category %> 
    </li> 
    <% end %> 
</div> 

Categories_controller.rb

def index 
    @title = "All categories" 
    @categories = Category.paginate(:page => params[:page]) 
    end 

    def show 
    @category = Category.find(params[:id]) 
    @title = @category.title 
    end 

    def new 
    @category = Category.new 
    @title = "Add category" 
    end 

    def create 
    @category = Category.new(params[:category]) 
    if @category.save 
    flash[:success] = "Successfully added category" 
    redirect_to categories_path 
    else 
    @title = "Sign up" 
    render 'new' 
    end 
end 

def edit 
    @category = Category.find(params[:id]) 
    @title = "Edit category" 
end 

def update 
    @category = Category.find(params[:id]) 
    if @category.update_attributes(params[:category]) 
    flash[:success] = "Category updated." 
    redirect_to categories_path 
    else 
    @title = "Edit user" 
    render 'edit' 
    end 
end 

def destroy 
    Category.find(params[:id]).destroy 
    flash[:success] = "User destroyed." 
    redirect_to categories_path 
end 

エンド

答えて

3

@categoriesはindexアクションでのみ定義されています。私は、すべてのページ上でレイアウトの一部として_menu.html.erbを使用していると仮定しています。

@categoriesは、例外の原因となるその他の場合はnilになります。

基本的に、すべてのアクションのカテゴリを定義する2つの方法があります。 一つは、私は好きではないので、私は個人的に第二の方法を好む

<% Category.all.each do |category| %>

のように部分的に呼び出しを行うには、あなたのコントローラにフィルタの前に

class CategoriesController 
    before_filter :load_categories 

    ... 

    private 

    def load_categories 
    @categories = Category.all 
    end 
end 

を使用して、他の方法だろうビューでトリガーされたデータベース呼び出し。

+0

さて、この問題を解決するにはどうすればよいですか? @categories = Category.allはどこで呼び出されますか?ある静的なページのホームに追加すると動作しますが、これを自分のコードのすべてのメソッドに追加したくありません。 – user1107922

+0

答えを更新しました。 – iltempo

+0

ありがとうございました:) – user1107922

関連する問題