Cocoon gem嵌套表单编辑报错:找不到资源模板求助
Hey there, let's work through this frustrating issue—your form saves perfectly fine, but throws a missing template error when editing? Let's break down the most likely fixes tailored to your setup with models/basic.rb, models/social_network.rb, controllers/basic_controller.rb, and the nested form views basics/_form.html.erb and basics/_social_network_fields.html.erb.
Common Causes & Fixes
1. Missing or Misnamed Edit Template
Rails automatically looks for a template matching your controller action by default. If your BasicController#edit action doesn't explicitly specify what to render, it will try to load views/basics/edit.html.erb.
- Check if the template exists: If
edit.html.erbis missing, you have two straightforward options:- Create
views/basics/edit.html.erb(it can simply render your existing form with<%= render 'form' %>) - Or, update your controller's edit action to directly reuse the form template:
# in controllers/basic_controller.rb def edit @basic = Basic.find(params[:id]) render 'form' # Skips looking for edit.html.erb and uses your existing form end
- Create
2. Incorrect Paths in Render Calls
Double-check that all your render statements point to the right template locations, especially for the nested _social_network_fields.html.erb partial. A tiny typo here is a common culprit.
- In your
_form.html.erb, when rendering the nested fields, confirm the path matches where the partial lives:<%= f.fields_for :social_networks do |sn_form| %> # If _social_network_fields is in views/basics/ (same directory as _form) <%= render 'social_network_fields', f: sn_form %> # If it's stored in views/shared/, use this instead: # <%= render 'shared/social_network_fields', f: sn_form %> <% end %>
3. Update Action's Failure Branch Render Target
When your update fails (e.g., due to validation errors), your controller needs to render a template that actually exists. If you're using render :edit, you need the edit.html.erb template. If you want to reuse the form directly, switch to render 'form':
# in controllers/basic_controller.rb def update @basic = Basic.find(params[:id]) if @basic.update(basic_params) redirect_to @basic, notice: 'Basic record updated successfully!' else # Use this to reuse your existing form template (no need for edit.html.erb) render 'form' # OR use this only if edit.html.erb exists in your views/basics/ folder: # render :edit end end
4. Hidden Syntax Errors in Partials
Sometimes a syntax error in your nested partial (like an unclosed <% end %> tag or misspelled variable) can trick Rails into throwing a "missing template" error instead of the actual syntax error.
- Test this quickly by temporarily commenting out all content in
_social_network_fields.html.erband reloading the edit page. If the page loads successfully, you know the issue is in that partial—go line by line to fix the syntax mistake.
内容的提问来源于stack exchange,提问作者Jaeger

