Rails嵌套属性编辑报错:form_for参数为空问题求助
Hey there! Let's get to the bottom of why your SiteAssets edit form is throwing that error. The issue boils down to one (or both) of your instance variables @site or @site_asset being nil when the _form.html.erb partial loads. Here's how to fix it step by step:
1. Check Your Nested Controller's edit and update Actions
In your Sites::SiteAssetsController, you need to explicitly load both the parent @site and the child @site_asset in the edit and update actions. If you skipped this, the form will have nothing to bind to.
Update your controller code to look like this:
class Sites::SiteAssetsController < ApplicationController def edit # Load the parent Site first @site = Site.find(params[:site_id]) # Then find the specific SiteAsset belonging to that Site @site_asset = @site.site_assets.find(params[:id]) end def update @site = Site.find(params[:site_id]) @site_asset = @site.site_assets.find(params[:id]) if @site_asset.update(site_asset_params) redirect_to [@site, @site_asset], notice: "Site asset updated successfully!" else # If validation fails, re-render the edit form (which requires both instance variables) render :edit end end private # Make sure you're permitting all necessary attributes for SiteAsset def site_asset_params params.require(:site_asset).permit(:name, :file_url, :description) # Replace with your actual attributes end end
2. Verify Your Nested Routes Are Set Up Correctly
Double-check that your config/routes.rb has the nested resources configured properly. This ensures the site_id and id parameters are passed to the controller:
Rails.application.routes.draw do resources :sites do resources :site_assets # This creates nested routes like /sites/:site_id/site_assets/:id/edit end end
3. Optional: Add a Safety Check in the Form Partial
While fixing the controller should resolve the issue, you can add a quick safety check in _form.html.erb to handle edge cases where variables might still be nil:
<% if @site.present? && @site_asset.present? %> <%= form_for [@site, @site_asset] do |form| %> <!-- Your form fields go here --> <% if @site_asset.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@site_asset.errors.count, "error") %> prohibited this site asset from being saved:</h2> <ul> <% @site_asset.errors.each do |error| %> <li><%= error.full_message %></li> <% end %> </ul> </div> <% end %> <!-- Example form field --> <div class="field"> <%= form.label :name %> <%= form.text_field :name %> </div> <div class="actions"> <%= form.submit %> </div> <% end %> <% else %> <p>Oops! Could not load the site or site asset. Please try again.</p> <% end %>
The key fix here is ensuring your controller properly loads both @site and @site_asset before rendering the edit form. That way, the form_for helper has valid instances to work with, and the error should disappear.
内容的提问来源于stack exchange,提问作者Jeremy Bray

