pluginaweek / state_machine

Adds support for creating state machines for attributes on any Ruby class
http://www.pluginaweek.org
MIT License
3.74k stars 507 forks source link

Mongoid (v3) field aliases keep state from being saved #270

Open xentek opened 11 years ago

xentek commented 11 years ago

We defined our Mongoid field with an alias. Here is a simple example class to illustrate the issue:

class MyModel
  include Mongoid::Document

  field :st, as: :status, type: String

  state_machine :status, initial: :draft do
    event :publish do
      transition :draft => :published
    end
  end
end

The issue is exhibited when you have an instance of MyMongoid and try to call publish! on it. The status field is changed to published, but the model is not saved. If you try to save it manually (with save or save!), the status is changed back to draft when you reload or re-query the object from the database.

Fixing it was easy, we just renamed the field to :status and left the alias out. Not ideal, but did take a lot of debugging to figure out what was causing the behaviour explained above. I also reason that we could have just changed the state machine to use the real field name (e.g. state_machine :st ...) and it would have worked, though that would muddy up our domain and hide our intentions behind the abbreviation.

If I get some free time soon, I'll try to work up a patch, but right now I have people to see, fat to chew, and a feature to ship. :shipit:

More info on the field aliasing feature: http://mongoid.org/en/mongoid/docs/documents.html#field_aliasing (you may need to scroll up a little, the hash anchor was a little screwy for me)

Cheers, and thanks for an otherwise super solid library.