現在Webアプリケーションを作成しており、ヘッダーにカテゴリー別のリンクを作成し、そこをクリックするとcategory/1, category/2のように対応したページへ飛びたいのだが、うまくいきません。
【こちらで実施したこと】
ヘッダー部分に下記項目を追加
<li> <% @categories.each do |category| %> </li> <li><%= link_to "#{category.name}", "#" %></li> <% end %> #とりあえずリンク先は"#"にしてます
indexページに接続すると下記エラー発生
NoMethodError in Videos#index Showing /Users/tky/Myapp/music_app/app/views/layouts/_header.html.erb where line #34 raised: undefined method `each' for nil:NilClass
すべてのページにヘッダーが存在するため、対応しているコントローラー(video_controller.rb)にCategory.allを追加
ruby
1 def index 2 @videos = Video.all 3 @categories = Category.all 4 end 5 6 def show 7 @video = Video.find_by(id: params[:id]) 8 @categories = Category.all 9 end 10 11 def new 12 @video = Video.new 13 @categories = Category.all 14 end 15
==============【ここからエラー発生】===================
この状態でヘッダー部分にリンク先を追加
<li> <% @categories.each do |category| %> </li> <li><%= link_to "#{category.name}", category_path %></li> <% end %>
ルーティング
categories GET /categories(.:format) categories#index POST /categories(.:format) categories#create new_category GET /categories/new(.:format) categories#new edit_category GET /categories/:id/edit(.:format) categories#edit category GET /categories/:id(.:format) categories#show PATCH /categories/:id(.:format) categories#update PUT /categories/:id(.:format) categories#update DELETE /categories/:id(.:format) categories#destroy videos GET /videos(.:format) videos#index POST /videos(.:format) videos#create new_video GET /videos/new(.:format) videos#new edit_video GET /videos/:id/edit(.:format) videos#edit video GET /videos/:id(.:format) videos#show PATCH /videos/:id(.:format) videos#update PUT /videos/:id(.:format) videos#update DELETE /videos/:id(.:format) videos#destroy
下記の様なエラーが発生しました
ActionController::UrlGenerationError in Videos#index Showing /Users/tky/Myapp/music_app/app/views/layouts/_header.html.erb where line #35 raised: No route matches {:action=>"show", :controller=>"categories"}, missing required keys: [:id]
idを指定しろということなのだと思いますが、どう指定すれば良いのかわかりません。
【コード】
routes.rb resources :categories
categories_controller.eb def index @categories = Category.all end def show @category = Category.find_by(id: params[:id]) end end
何かわかるかたアドバイスを頂けないでしょうか。
よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。