问题
I have installed the gem
gem 'state_machine', :require => 'state_machine/core'
I've bundled.
I've migrated a column state type string to the relevant Table.
My model looks like this
belongs_to :user
belongs_to :patient
validates :patient_id, uniqueness: {scope: [:email]}
state_machine :initial => :unseen do
event :look do
transition :unseen => :seen
end
end
When I ran
rails c
Table.all
I got the below error in reference to the model page where I referenced state_machine
undefined method `state_machine' for Table
I commented out the relevant portion of the model page, deleted all the previously created records in that table, uncommented out the state_machine portion of the model, and then from within rails c I could successfully create a record but the value for state was nil.
Equally disturbing when I try to load my front page I'm using Angular and it makes an API call to retrieve records which returns a 500 error. The console log shows
NoMethodError (undefined method `state_machine' for #<Class...
This person (state_machine gem integration with rails 4) had the same issue and needed to restart their server. I have restarted the servers several times, as well as closing terminal and then starting the servers.
My Gemfile.lock has this file - state_machine (1.2.0), and the bundle showed no errors.
Edit:
Despite having been able to call Table.all successfully after deleting all previous records in that table (requiring commenting out the state machine code) and then, after uncommenting said code, being able to create and view a record, if I then leave the console and return to the console and repeat the exact same request (Table.all) it leads to the same error of undefined method 'state_machine'
回答1:
I think you have two options.
Option 1
Either you should drop the :require => 'state_machine/core'
part. So the new line would look just like this:
gem 'state_machine'
Option 2
Or add this line to your class:
extend StateMachine::MacroMethods
For example:
require 'state_machine/core'
class Vehicle
extend StateMachine::MacroMethods
state_machine do
# ...
end
end
Explanation
Loading of the file 'state_machine/core'
disables extension of Class
. That means that method state_machine
will not be available in any class unless you call extend StateMachine::MacroMethods
.
Details here: https://github.com/pluginaweek/state_machine#core-extensions
Bonus hint
Consider using state_machines
gem (ending with "s") instead of original state_machine
gem.
gem 'state_machines'
gem 'state_machines-activerecord'
The original is not maintained anymore (I am not sure why) but the new one is updated from time to time and it might prevent some errors.
来源:https://stackoverflow.com/questions/23400107/state-machine-gem-rails-4-undefined-method-state-machine-for-class0x007f