前提
Ruby on Rails6でcocoonの使用方法を勉強するために、簡易アプリを作成中です。
フロント部分は現状全く考慮していません。
レシピに対してその材料を追加・削除できるようなイメージです。
cocoonの導入は問題なく出来ていると思います。
発生している問題・エラーメッセージ
ActionView::MissingTemplate in Recipes#new Missing partial recipes/_ingredient_fields, application/_ingredient_fields with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :jbuilder]}. Searched in: * "/Users/projects/cocoon_app/app/views" * "/Users/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actiontext-6.0.5/app/views" * "/Users/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actionmailbox-6.0.5/app/views"
該当のソースコード
views/recipes/new.html.erb
erb
1<h1>レシピの食材入力</h1> 2<%= form_with model: @recipe, url: recipes_new_path, local: true do |f| %> 3 <%= f.text_area :name %> 4 5 <%= f.fields_for :ingredients do |t| %> 6 <%= render "recipe_ingredient_fields", f: t %> 7 <% end %> 8 9 <%= link_to_add_association "追加ボタン", f, :ingredients %> 10<% end %>
views/recipes/_recipe_ingredient_fields.html.erb
erb
1<div class="nested-fields"> 2 <%= f.collection_select(:ingredient_id, {}, :id, :name, {}) %> 3 <%= f.number_field :quantity %> 4 <div>個</div> 5 <%= link_to_remove_association "削除", f %> 6</div>
controllers/recipes_controller.rb
ruby
1class RecipesController < ApplicationController 2 def new 3 @recipe = Recipe.new 4 @ingredients = @recipe.ingredients.build 5 end 6 7 def create 8 @recipe = Recipe.new(recipe_params) 9 if @recipe.save 10 redirect_to root_path 11 else 12 render action: :new 13 end 14 end 15 16 private 17 18 def recipe_params 19 params.require(:recipe).permit(:name, ingredients_attributes: [:id, :ingredient_id, :quantity, :_destroy]) 20 end 21end
models/recipe.rb
ruby
1class Recipe < ApplicationRecord 2 has_many :ingredients, dependent: :destroy 3 accepts_nested_attributes_for :ingredients, allow_destroy: true 4end
models/ingredient.rb
ruby
1class Ingredient < ApplicationRecord 2 belongs_to :recipe 3end
試したこと
エラーとなっている部分をコメントアウトすると、問題なくビューが表示されました。
その際、<%= link_to_remove_association "削除", f %>
の記述により、削除のリンクが作成されていていました。
クリックすると削除されることから、cocoonの導入自体は問題ないのだと思われます。
また、fields_for内に入れるのでは?という記事も見かけたので位置を動かしてみましたが、変化なしでした。
何か基本的な部分の認識違いがあるのではないかと思うのですが、自分では気づけなかったので、ご教示いただけると幸いです。
補足情報(FW/ツールのバージョンなど)
Rails 6.0.5
ruby 2.6.5
あなたの回答
tips
プレビュー