ruby-on-railsancestry

Rails ancestry with nil parent


I'm building a hierarchical category in Rails using Ancestry, and I allow the user to choose the parent of the object they're creating. I display the existing categories using a dropdown:

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

As long as the user chooses an existing node, all is well. If the user chooses the blank in the dropdown, I would expect Ancestry to create a root node, but instead the form throws an "is invalid" error.

My controller isn't doing anything mindblowing:

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 newer to Rails, so I'm not sure how to attack this problem. Is there a configuration for Ancestry that I missed, or is this a form validator being over-protective perhaps?


Solution

  • That happens because ancestry can't be nil and it's a bad idea to change it manually because all the gem's behavior is based on this attribute. For such cases gem has another parent_id attribute which you should use in your form.

    There is a good explanation in gem's wiki how to build form using ancestry

    Hope it helps