我今天第一次尝试the Ancestry gem作为内容管理系统的一部分,并且希望能够手动创建节点并将它们连接在一起。换句话说,上下文没有规定任何新节点的父节点是什么,不像每个人都读过的许多线程讨论示例。
目前,当我尝试保存(创建或更新)具有不存在的parent_id(“4”)的节点时,我收到错误:
ActiveRecord::RecordNotFound in TreesController#update
Couldn't find Tree with 'id'=4
我希望将任何引用不存在的父节点的节点分配给没有父节点。我该怎么做?
这是trees_controller.rb的相关部分:
def create
@tree = Tree.new(tree_params)
if @tree.save
redirect_to trees_url, notice: "Tree was successfully created"
else
render :new
end
end
...
private
def tree_params
params.require(:tree).permit(:name, :value, :note, :parent_id)
end
由于
答案 0 :(得分:0)
经过一周的研究,我设法对它进行了分类。对于那些遇到同样障碍的人来说,这是一个解决方案:
def create
parent_exists = Tree.exists?(params[:tree][:parent_id])
if !parent_exists
params[:tree][:parent_id] = nil
note = "Parent node didn't exist so set to nil."
end
@tree = Tree.new(tree_params)
if @tree.save
redirect_to trees_url, notice: "Node was successfully created. " + note.to_s
else
render :new, notice: "There was an error saving this node. Please try again."
end
end