没有父母的Rails祖先

kid*_*rew 4 ruby-on-rails ancestry

我正在使用Ancestry在Rails中构建一个分层类别,我允许用户选择他们正在创建的对象的父级.我使用下拉列表显示现有类别:

<%= f.input :ancestry, collection: Category.sorted_list %>
Run Code Online (Sandbox Code Playgroud)

只要用户选择现有节点,一切都很好.如果用户在下拉列表中选择空白,我希望Ancestry创建一个根节点,但是表单会抛出"无效"错误.

我的控制器没有做任何令人费解的事情:

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 
Run Code Online (Sandbox Code Playgroud)

我是Rails的新手,所以我不确定如何解决这个问题.我错过了Ancestry的配置,还是这个表格验证器可能过度保护?

Ser*_*nin 7

发生这种情况是因为ancestry不可能nil并且手动更改它是一个坏主意,因为所有gem的行为都基于此属性.对于这种情况,gem有另一个parent_id属性,您应该在表单中使用.

gem的wiki中有一个很好的解释如何使用构建表单ancestry

希望能帮助到你