Rails pedigree with nil parent

I create a hierarchical category in Rails using Ancestry, and I allow the user to select the parent of the object they create. I show existing categories using the drop down menu:

<%= f.input :ancestry, collection: Category.sorted_list %> 

As long as the user selects an existing node, all is well. If the user selects empty from the drop-down list, I expect Ancestry to create a root node, but instead the form throws an "invalid" error.

My controller does nothing:

 def update @category = Category.find(params[:id]) respond_to do |format| if @category.update_attributes(params[:category]) format.html { redirect_to @category, notice: 'Category was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @category.errors, status: :unprocessable_entity } end end end 

I'm new to Rails, so I'm not sure how to attack this issue. Is there a configuration for Ancestry that I missed, or is it a form validator that might be overly secure?

+4
source share
2 answers

This is because ancestry cannot be nil , and it is a bad idea to change it manually, because all gem behavior is based on this attribute. For such cases, gem has another parent_id attribute that you should use in your form.

The gem wiki has a good explanation on how to build a form using ancestry

Hope this helps

+6
source

Ancestry validates its field with this :

 # Validate format of ancestry column value validates_format_of ancestry_column, :with => Ancestry::ANCESTRY_PATTERN, :allow_nil => true 

But you cannot pass nil value in forms. So I did this:

 before_validation do self.ancestry = nil if self.ancestry.blank? end 
+1
source

All Articles