我今天第一次尝试将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
感谢
经过一周的研究,我终于把它整理好了。以下是针对那些遇到相同障碍的人的解决方案:
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