使用Mongoid,Ancestry递归保存记录

时间:2013-05-24 10:56:04

标签: ruby-on-rails ruby-on-rails-3 mongodb mongoid

我在[{1}}模型中嵌入了一个模型Line Items。在Line create view中,我提供了定义多个嵌套级别的订单项的功能。

以下是Line的随机快照:

param[:line]

在Line #create中,我有:

=> {"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"}}}

在Line#save_lines中,我有:

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

LineItem模型如下所示:

# 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

在Line模型中,我有:

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

按预期工作。但是,有没有更好的方法用Ancestry递归保存line_items?

1 个答案:

答案 0 :(得分:0)

我认为您的代码看起来很好。我只是重构了它。 怎么样:

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