Rails - Mongoid : newly added fields in model giving nil for old data objects

I have model as follows:

class User
  include Mongoid::Document
  field :name
end

After saving a few user objects to the database I added some more fields:

class User
  include Mongoid::Document
  include Mongoid::Timestamps::Created
  field :name
  field :birthdate
end

Now, I expect I can use the following snippet:

@user = User.all
@user.each do |u|
   puts u.name
   puts u.birthdate.strftime(#someFormat)
   puts u.created_at.strftime(#someFormat)
end

Unfortunately, because my old user objects don't have birthdate keys, I receive this error: strftime called on nil class.

Question:

  • How can I handle such cases with Mongoid? In MySQL, when a column is added it gets added to old rows as well. But if I see in MongoDB, it doesn't add new fields as keys for old data.
  • This problem also exists with the created_at field as old data doesn't have that field either.

I am looking for good way to solve this, checking for nil conditions each time is not a scalable option because the number of fields will continue increasing.

Answers


You could also add a default to your new field, which would give all your old records a fallback value.

class User
  include Mongoid::Document
  include Mongoid::Timestamps::Created

  field :name
  field :birthdate, :type => Date, :default => Date.new(1970,1,1)
end

You can update your models which are missing created_at values, but just running something simple in your rails console:

User.all.each{ |u| u.update_attributes(:created_at => Time.now) if u.created_at.nil? }

1) You can check for nil value for those fields:

@user = User.all
@user.each do |u|
   puts u.name
   puts u.birthdate.strftime(#someFormat) if u.birthdate
   puts u.created_at.strftime(#someFormat) if u.created_at
end

2) You can update all your old models with actual not nil values for those fields. You can do it with mondodb update (read more here) or by writing ruby script like this:

User.all.select{|u| u.birthdate.nil? || u.created_at.nil?}.each do |u|
  u.update_attributes(:birthdate => Date.today, :created_at => Time.now)
end

birthdate and created_at attributes are filled with sample values.


Need Your Help

php Xcart Setup using smarty template

php smarty x-cart

i want to run a existing product store site on my localhost wamp server i changed all the Config variables in config file

Javascript rotate sprite?

javascript html5 rotation sprite angle

So I am working on this game with a friend. And we are having some trouble getting the sprite to rotate. The angle is always -2.356194490192345. Can anyone tell me whats wrong with the code below?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.