查找后的Mongoid文件持久化

时间:2011-10-02 05:08:13

标签: ruby-on-rails inheritance mongodb model mongoid

我无法将文档保存在mongoid中。我的控制器中有以下代码片段:

params[:user][:residence_attributes][:locations_attributes].each do |num,location_attributes|
  zipcode = Location.find(location_attributes[:id])

  if !zipcode.update_attributes(location_attributes)
    puts "fail"
    fail = true
  end

  puts "zipcode again #{zipcode}"
  puts "zipcode number #{zipcode.number}"
  puts "zipcodes = #{Zipcode.count}" 
  zipcode = Zipcode.find(@user.residence.locations[0].id)
  puts "zipcode again #{zipcode}"
  puts "zipcode number #{zipcode.number}"
  puts "zipcodes = #{Zipcode.count}" 
  zipcode = Zipcode.find(@user.residence.locations[0].id)
  puts "zipcode again #{zipcode}"
  puts "zipcode number #{zipcode.number}"
  puts "zipcodes = #{Zipcode.count}" 
end

它产生以下输出:

zipcode again #<Zipcode:0x000000063826a0>
zipcode number 11210
zipcodes = 1
zipcode again #<Zipcode:0x00000006348860>
zipcode number 
zipcodes = 1
zipcode again #<Zipcode:0x00000006340ef8>
zipcode number 
zipcodes = 1

所以问题是当我第二次和第三次找到文档时,为什么zipcode id会改变?

这是一个问题,因为文档不会持久存在。

我有以下型号:

class Zipcode < Location
  include Mongoid::Document
  attr_accessible :number
  attr_accessor :number

  validates_presence_of :number
  validate :check_zipcode
end

class Location
  include Mongoid::Document

  attr_accessible :latitude, :longitude
  belongs_to :locatable, polymorphic: true
end

class UserResidence
  include Mongoid::Document

  has_many :locations, as: :locatable

  embedded_in :user, :inverse_of => :residence

  attr_accessible :locations_attributes
  accepts_nested_attributes_for :locations, autosave: true

  #validates_presence_of :locations
  #validates :locations, :length => {:minimum => 1}
end

由于

2 个答案:

答案 0 :(得分:1)

你要保存文件吗?

尝试将自动保存设置为true

请参阅:     http://mongoid.org/docs/upgrading.html (在页面上搜索自动保存)

答案 1 :(得分:0)

根据http://mongoid.org/docs/relations/nested_attributes.html,您需要在autosave: true上设置has_many :locations

has_many :locations, as: :locatable, autosave: true
accepts_nested_attributes_for :locations