开发者

Mongoid document persistence after find

I having trouble persisting my documents in mongoid. I have the following code fragment in my controller:

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 aga开发者_开发技巧in #{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

And it yields the following output:

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

So the question is why does the zipcode id change when I find the document the second and third time?

This is a problem because the document does not persist.

I have the following models:

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

Thanks


are you saving the document?

try to set autosave to true

see: http://mongoid.org/docs/upgrading.html (search on the page for autosave)


As per http://mongoid.org/docs/relations/nested_attributes.html you need to set autosave: true on has_many :locations.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜