0

我有一个Line Items嵌入模型的Line模型。在 Line create 视图中,我提供了定义多个嵌套级别的行项目的能力。

这是一个随机快照param[: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"}}}

在 Line#create 中,我有:

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

在 Line#save_lines 中,我有:

# 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

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

4

1 回答 1

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
于 2013-05-24T11:41:36.333 回答