加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何在rails中创建递归函数,它将返回父级的所

发布时间:2020-12-17 03:03:27 所属栏目:百科 来源:网络整理
导读:我有一个方法如图所示: def all_pages_and_its_n_level_child @parent_pages = Page.where(:parent_id = params[:page_id]) #this will give me all child of this page for page in @parent_pages child_exists=Page.where(:parent_id=page.id) #this will
我有一个方法如图所示:

def all_pages_and_its_n_level_child

     @parent_pages = Page.where(:parent_id => params[:page_id])
     #this will give me all child of this page
     for page in @parent_pages
          child_exists=Page.where(:parent_id=>page.id)
          #this will give all children of that page
          #*I want to make this loop further so that i can check to N-levels,#this is only for two levels*
     end


end

解决方法

这是一些样本(它没有经过测试!但它会给你一些线索):

def all_children(children_array = [])
  children = Page.where(parent_id: self.id)
  children_array += children.all
  children.each do |child|
    child.all_children(children_array)
  end
  children_array
end

所以这是递归,它将尝试从父级中查找所有子级(也嵌套).我知道这是非常丑陋和低效的,但我希望ii会给你一个关于找到嵌套元素的线索.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读