我在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
谢谢
最佳答案
你在保存文件吗?
尝试将autosave设置为true
见:
http://mongoid.org/docs/upgrading.html
(在页面上搜索自动保存)
关于ruby-on-rails - 查找后的Mongoid文件持久化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7624732/