首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails Ancestry gem:保存节点时确保父节点存在

Rails Ancestry gem:保存节点时确保父节点存在
EN

Stack Overflow用户
提问于 2014-09-28 08:40:31
回答 1查看 592关注 0票数 0

我今天第一次尝试将the Ancestry gem作为内容管理系统的一部分,并希望能够手动创建节点并将它们连接到树中。换句话说,上下文并不规定任何新节点的父节点是什么,这与每个人都读过的许多线程讨论示例不同。

此时,当我尝试用不存在的parent_id ("4")保存(创建或更新)一个节点时,我得到了错误:

代码语言:javascript
复制
ActiveRecord::RecordNotFound in TreesController#update
Couldn't find Tree with 'id'=4

我希望所有引用不存在的父节点的节点都被指定为没有父节点。我该怎么做?

以下是trees_controller.rb的相关部分:

代码语言:javascript
复制
  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

谢谢

EN

回答 1

Stack Overflow用户

发布于 2014-10-04 16:54:17

经过一周的研究,我终于把它整理好了。对于那些遇到相同障碍的人,这里有一个解决方案:

代码语言:javascript
复制
  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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26080534

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档