"users"ビューでこのコードを使用しましたが、問題はありませんでした。<%if current_user.admin? %>しかし、それを別のコントローラに関連付けられた一連のビューで使用すると、「No method Error」がスローされます。<%if current_user.admin? "と表示された場合、Railsアプリケーションは" no method error "を返します。 %>
背景:このアプリでは、管理者がスカベンジャーの狩猟を作成できます。管理者は狩りを削除できるはずです。私はすべてを構成する方法を知っていると思ったが、明らかに何かが足りない。ここに私のコードは次のとおりです。
controller.rb
class HuntsController < ApplicationController
def index
@title = "All Hunts"
@hunts = Hunt.order("name ASC")
end
def show
@hunt = Hunt.find(params[:id])
@title = @hunt.name
end
def new
@hunt = Hunt.new
@title = "New Hunt"
end
def create
@hunt = Hunt.new(params[:hunt])
if @hunt.save
flash[:success] = "Hunt created!"
redirect_to hunts
else
@title = "New Hunt"
render 'new'
end
end
def edit
@hunt = Hunt.find(params[:id])
@title = "Edit hunt"
end
def delete
Hunt.find(params[:id]).destroy
flash[:success] = "Hunt destroyed."
redirect_to index
end
end
ビュー/ Index.html.erb
<h1>All Hunts</h1>
<ul>
<% @hunts.each do |hunt| %>
<%= render hunt %>
<% end %>
</ul>
<%= link_to("Create New Hunt", '/hunts/new') %>
ビュー/ _hunt.html.erb
<li>
<%= link_to hunt.name, hunt %>
<% if current_user.admin? %>
<%= link_to "delete", hunt, :method => :delete, :confirm => "You sure?",
:title => "Delete #{hunt.name}" %>
<% end %>
</li>
エラーメッセージしようとしたとき頭に/狩り:
NoMethodError in Hunts#index
Showing ...../app/views/hunts/_hunt.html.erb where line #3 raised:
undefined method `admin?' for nil:NilClass
正確で完全なエラーは何ですか? –
私はちょうど私の質問のメインセクションにエラー情報を追加しました。これは、nilクラスのエラーです。 –
'current_user'はこのコントローラで定義されていません。 –