Ruby on rails 使用Mongoid、祖先递归保存记录

Ruby on rails 使用Mongoid、祖先递归保存记录,ruby-on-rails,ruby-on-rails-3,mongodb,mongoid,Ruby On Rails,Ruby On Rails 3,Mongodb,Mongoid,我在行模型中嵌入了一个模型行项目。在“行创建”视图中,我提供了定义行项目的多个嵌套级别的功能 下面是参数[:line]的随机快照: => {"title"=>"Hello", "type"=>"World", "line_items"=>{"1"=>{"name"=>"A", "position"=>"1", "children"=>{"1"=>{"name"=>"A1", "position"=>"1", "

我在
模型中嵌入了一个模型
行项目
。在“行创建”视图中,我提供了定义行项目的多个嵌套级别的功能

下面是参数[:line]的随机快照:

=> {"title"=>"Hello", "type"=>"World", "line_items"=>{"1"=>{"name"=>"A", 
    "position"=>"1", "children"=>{"1"=>{"name"=>"A1", "position"=>"1", 
    "children"=>{"1"=>{"name"=> "A11", "position"=>"1"}, "2"=>{"name"=>"A12",
    "position"=>"2"}}}, "2"=>{"name"=>"A2", "position"=>"2"}}}, "3"=>
    {"name"=>"B", "position"=>"3"}}}
在“创建”行中,我有:

def create
  @line = Line.new(params[:line])

  if @line.save
    save_lines(params[:line][:line_items])
    flash[:success] = "Line was successfully created."
    redirect_to line_path 
  else
    render :action => "new"
  end
end
在“保存”行中,我有:

# Save children up to fairly infinite nested levels.. as much as it takes!
def save_lines(parent)
  unless parent.blank?
    parent.each do |i, values|
      new_root = @line.line_items.create(values)
      unless new_root[:children].blank?
        new_root[:children].each do |child|
          save_lines(new_root.children.create(child))
        end
      end
    end
  end
end
LineItem模型如下所示:

class LineItem
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Ancestry
  has_ancestry

  # Fields
  field :name,        type: String,
  field :type,        type: String
  field :position,    type: Integer
  field :parent_id,   type: Moped::BSON::ObjectId

  attr_accessible :name, :type, :url, :position, :parent_id

  # Associations
  embedded_in :line, :inverse_of => :line_items
end
在直线模型中,我有:

# Associations
embeds_many :line_items, cascade_callbacks: true

它的工作正如预期的那样。但是,有没有更好的方法可以使用祖先递归保存行项目?

我认为您的代码看起来不错。我刚刚重构了它。 那么:

def save_lines(parent)
  parent.each do |i, values|
    #get children hash if any
    children = values.delete("children")
    # create the object with whatever remain in values hash
    @line.line_items.create(values)
    # recurse if children isn't empty
    save_lines(children) if children
  end
end

我几天前解决了这个问题。对递归创建对象有着非常相似的需求。但是你是否也需要将内部对象与外部对象相关联(有很多)?在我的例子中,它们必须是。不,内部对象没有关联。实际上,我规范了它的关联,形成了一个平面文档(表)。下面是
的文档接受
的_嵌套_属性_:这使线模型的参数散列包含嵌入的线项目,并自动创建对象。(也可在ActiveRecord中获得,仅供参考)