Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix "missing attribute: state" when state attribute is not included in the query #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

smartinm
Copy link

When limiting the fields returned from the database the error is raised:

[1] pry(main)> i = Model.all.only(:_id).first
ActiveModel::MissingAttributeError: Missing attribute: 'state'.
from /Users/sergio/.rvm/gems/ruby-2.2.0/gems/mongoid-4.0.2/lib/mongoid/attributes.rb:97:in `read_attribute'

This PR excludes state initialization when the attribute is not included in the query.

@look
Copy link

look commented Mar 10, 2016

I just ran into this problem when upgrading an application from Mongoid 3 to Mongoid 5. This patch fixes the issue. It would be great to have it merged and push out a new release.

@scebotari
Copy link

Had the same issue when upgrading my application. Is this PR going to be merged?

image

@smartinm Thanks for this fix. Worked for my case too.

@sos4nt
Copy link

sos4nt commented May 21, 2021

Since the problem still exists and this PR doesn't seem to get merged, here's a workaround:

The error is (at least in my case) caused by the state's initial value because the corresponding attribute is missing from the document when using only. This can be circumvented by setting the initial value in a lambda.

So instead of:

state_machine :state, initial: :parked do
  # ...
end

You can write:

state_machine :state, initial: -> { :parked } do
  state :parked # <- only needed when there's no transition to or from :parked

  # ...
end

This defers setting the initial value until you actually attempt to interact with the state machine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants