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
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/state_machines/integrations/mongoid.rb
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ def apply_pre_processed_defaults
defaults = {}
self.class.state_machines.initialize_states(self, :static => :force, :dynamic => false, :to => defaults)
defaults.each do |attr, value|
send(:"\#{attr}=", value) unless attributes.include?(attr)
send(:"\#{attr}=", value) unless has_attribute?(attr) || attribute_missing?(attr)
end
super
end
Expand Down
26 changes: 26 additions & 0 deletions test/machine_with_limited_fields_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
require_relative 'test_helper'

class MachineWithLimitedFieldsTest < BaseTestCase
def setup
@model = new_model
@machine = StateMachines::Machine.new(@model, :initial => :parked)
@machine.state :idling

@record = @model.create
end

def test_should_not_set_value_when_exclude_field_in_query
record = @model.where(id: @record.id).only(:_id).first
assert_equal ["_id"], record.attributes.keys
end

def test_should_set_value_when_include_field_in_query
record = @model.where(id: @record.id).only(:_id, :state).first
assert_equal "parked", record.state
end

def test_should_fail_if_access_when_exclude_field_in_query
record = @model.where(id: @record.id).only(:_id).first
assert_raises(ActiveModel::MissingAttributeError) { record.state }
end
end