Rails嵌套分类(Ancestry gem):分类增改及下拉选择无法保存至数据库求助
Hey there, let's figure out why your Adcategory records aren't saving! Based on the code you shared, I spot two key issues that are likely causing the problem:
1. Mismatched Form Field for Parent Category
Looking at your _form.html.erb, you're using :adcategory_ids in the select field—but this is designed for many-to-many associations (like linking a single model to multiple Adcategories). Since you're building a nested parent/child category structure, you should be setting the parent_id field instead, which maps directly to your self-association setup.
Fix the form code like this:
<%= f.select(:parent_id, nested_dropdown(Adcategory.all.arrange), prompt: "Select Parent Adcategory", selected: @adcategory.parent_id ) %>
2. Unnecessary Parameter in Strong Params
In your adcategories_controller.rb, the adcategory_params method includes :adcategory_id—this doesn't align with your self-association (you're using parent_id as the foreign key for parent categories). This extra, unused parameter could be causing filtering conflicts that prevent saves.
Update your strong params to remove it:
def adcategory_params params.require(:adcategory).permit(:name, :parent_id) end
Bonus: Double-Check Your Model Association
Make sure your Adcategory model has the correct self-association configured (add optional: true to allow root categories with no parent):
class Adcategory < ApplicationRecord belongs_to :parent, class_name: "Adcategory", optional: true has_many :children, class_name: "Adcategory", foreign_key: "parent_id" end
How to Verify the Fix
To confirm everything works, add puts params.inspect at the start of your create action. This will print the submitted parameters to your server console, so you can check that name and parent_id are being passed correctly and are permitted by your strong params.
After making these changes, your new and edit actions should save Adcategory records to the database without issues!
内容的提问来源于stack exchange,提问作者Charlie

