在Mongoid中保存时替换嵌入的文档

时间:2012-09-21 11:45:55

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

我希望能够在保存时替换MongoDB对象中的整个嵌入文档集 - HTML表单将包含整个新集。

我还希望它在保存之前验证所有内容 - 即不要删除旧文档,然后在添加时验证每个文档。

我已经提出了一个实现,但它没有坚持 - 没有新的嵌入式文档出现。更复杂的是涉及继承。这是(简化)我到目前为止的模型集:

class Person
  include Mongoid::Document
  embeds_many :vehicles
end

class Vehicle 
  include Mongoid::Document
  embedded_in :person
end

class Car < Vehicle
end

class Motorbike < Vehicle
end

为了计算用户提交表单时要实例化哪种车辆,我已将此方法添加到Person类:

def build_from_hash(hash)
   @vehicles= []
   hash.each do |idx, vehicle|
      if vehicle[:_type].constantize < Inclusion # Check for inheritance, for security
         self.vehicles.push vehicle[:_type].constantize.new(vehicle)
      end
   end
end

并修改控制器以调用它:

def submit_build
  @person= current_user.persons.find(params[:id])
  @person.build_from_hash(params[:vehicles]) if params.has_key? :vehicles

  respond_to do |format|
    if @person.save # Also tried: @person.update_attributes(inclusions: @person.vehicles)
      format.html { redirect_to @person, notice: 'Person was successfully updated.' }
      format.json { head :no_content }
    else
      format.html { render action: "build" }
      format.json { render json: @person.errors, status: :unprocessable_entity }
    end
  end
end

没有生成错误 - 页面重定向就像它有效一样,但是当我再次检查它时,没有嵌入文档。

使用Rails 3.2.8,Mongoid 3.0.5,MongoDB 1.8.3。

1 个答案:

答案 0 :(得分:0)

我想出了如何以更标准的Rails方式做到这一点,尽管有一些特殊行为的解决方法。

简短回答:Person类需要accepts_nested_attributes_for :vehicles,我必须从控制器中删除所有自定义内容,用标准更新操作替换操作。但它不会接受Vehicle子类的_type参数,除非Rails进程已经实例化了每个子类的对象,所以我被迫使用这样的初始化器来解决它:

Car.new
Motorbike.new

答案很长on the Mongoid Google group