state-machines / state_machines-activerecord Goto Github PK
View Code? Open in Web Editor NEWStateMachines Active Record Integration
Home Page: https://github.com/state-machines/state_machines-activerecord
License: MIT License
StateMachines Active Record Integration
Home Page: https://github.com/state-machines/state_machines-activerecord
License: MIT License
I was using state_machine (1.2.0), can I use state_machines-activerecord to replace state_machine with nothing of my code changed?
how do i implement such a case:
ticket with state in_progress
receives transition finish
. if ticket got reviewer_id
, it should change state to review
or complete
if there is no reviewer... i tried to do this:
event :finish do
if reviewer
transition in_progress: :review
else
transition in_progress: :complete
end
end
but it throws an error about there's no such a method for StateMachines
i tried to put this var into initialize block with no luck
When debugging scope creation, it appears that the #define_helper method is never called.
Here's the snippet from the link above:
def define_scopes(custom_plural = nil)
plural = custom_plural || pluralize(name)
[:with, :without].each do |kind|
[name, plural].map { |s| s.to_s }.uniq.each do |suffix|
method = "#{kind}_#{suffix}"
if scope = send("create_#{kind}_scope", method)
# Converts state names to their corresponding values so that they
# can be looked up properly
define_helper(:class, method) do |machine, klass, *states|
run_scope(scope, machine, klass, states)
end
end
end
end
end
The send
in debug mode equates to:
scope = send("create_without_scope", 'without_states')
This hits the no-op #create_without_scope.
How is the StateMachines::Integrations::ActiveRecord#create_without_scope
intended to be wired in to override the same method in machines.rb
?
I replaced my existing statemachine gem with this one so I could move up to Rails 4.2 and found that my observers aren't getting triggered.
Did that code get left behind? The documentation suggests that it should work with observers, but that's just been copied across from the old state_machine gem.
Where do I need to look in the code to fix this?
Hi!
Is it intended not to set save
as the default action in a transition or is something you are considering to add in the future?
This might be a related issue: pluginaweek/state_machine#327
Here I have a Car
class:
class Car < ActiveRecord::Base
attr_accessible :state_event
state_machine :state, initial: :parked do
event :drive do
transition :parked => :driving
end
event :stop do
transition :driving => :parked
end
event :turn_right do
transition :driving => :moving_right
end
end
end
c = Car.create!
c.update_attributes({ state_event: :turn_right })
The last command will successfully save the car and update the state attribute to :turn_right
, even though it should fail and return false, since a car cannot move from it's initial :parked
state to :moving_right
.
If I run:
c.state = :moving_right
c.save!
I will get the false
value properly returned.
after_save :model_callback
...
state_machine :state, initial: :inactive do
state :inactive, value: :inactive
state :active, value: :active
event :activate do
transition inactive: :active
end
end
def model_callback
send_confirmation_instructions if state_changed? && active?
end
# calling transition
my_model.activate
two activation emails are being sent, because callbacks are triggering twice.
I checked this with debugger (pry)
Been trying to make spree run with this project and noticed that every time I point the Gemfile to git or the gem release I get an error like this Undefined method 'state' for #<Post not initialized>
(tested on a bran new rails project as well). Whenever I point to the code using path
(local code) it works fine though. Have you experienced anything similar? (I might have something wrong in my local bundle config or set up and I can't see it right now)
For some reason the activerecord object is being initialized using the Machine#initialize
method rather than the ActiveRecord#initialize
.
To reproduce put a state machine on an activerecord object, e.g.:
class Post < ActiveRecord::Base
state_machine initial: :draft do
event :review do
transition to: :reviwed, from: :draft
end
event :complete do
transition to: :completed
end
end
end
Open rails c and then Post.new
.
Full stack trace of the error:
NoMethodError: undefined method `state' for #<Post not initialized>
from /Users/huoxito/.gem/ruby/2.1.3/gems/activemodel-4.2.0/lib/active_model/attribute_methods.rb:433:in `method_missing'
from /Users/huoxito/.gem/ruby/2.1.3/gems/state_machines-0.1.0/lib/state_machines/machine.rb:1053:in `read'
from /Users/huoxito/.gem/ruby/2.1.3/gems/state_machines-0.1.0/lib/state_machines/machine.rb:1904:in `initialize_state?'
from /Users/huoxito/.gem/ruby/2.1.3/bundler/gems/state_machines-activerecord-041af9e52445/lib/state_machines/integrations/active_record.rb:573:in `initialize_state'
from /Users/huoxito/.gem/ruby/2.1.3/gems/state_machines-0.1.0/lib/state_machines/machine_collection.rb:29:in `block in initialize_states'
from /Users/huoxito/.gem/ruby/2.1.3/gems/state_machines-0.1.0/lib/state_machines/machine_collection.rb:28:in `each_value'
from /Users/huoxito/.gem/ruby/2.1.3/gems/state_machines-0.1.0/lib/state_machines/machine_collection.rb:28:in `initialize_states'
from /Users/huoxito/.gem/ruby/2.1.3/gems/state_machines-0.1.0/lib/state_machines/machine.rb:1925:in `initialize'
from /Users/huoxito/.gem/ruby/2.1.3/gems/activerecord-4.2.0/lib/active_record/inheritance.rb:61:in `new'
from /Users/huoxito/.gem/ruby/2.1.3/gems/activerecord-4.2.0/lib/active_record/inheritance.rb:61:in `new'
from (irb):1
from /Users/huoxito/.gem/ruby/2.1.3/gems/railties-4.2.0/lib/rails/commands/console.rb:110:in `start'
from /Users/huoxito/.gem/ruby/2.1.3/gems/railties-4.2.0/lib/rails/commands/console.rb:9:in `start'
from /Users/huoxito/.gem/ruby/2.1.3/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:68:in `console'
from /Users/huoxito/.gem/ruby/2.1.3/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
from /Users/huoxito/.gem/ruby/2.1.3/gems/railties-4.2.0/lib/rails/commands.rb:17:in `<top (required)>'
from bin/rails:8:in `require'
from bin/rails:8:in `<main>'irb(main):002:0>
I should note that I am debugging this in a before_transition
.
I'm not sure what is going on yet, but I can see that the machine.rb#within_transaction is not run (which seems to evaluate this flag). With the active record integration, it runs the transaction every time. I'm not sure if it is overwriting that check in machine or what is occuring, but I cannot seem to turn off transactions as this code is always run:
# Runs a new database transaction, rolling back any changes by raising
# an ActiveRecord::Rollback exception if the yielded block fails
# (i.e. returns false).
def transaction(object)
result = nil
object.class.transaction do
raise ::ActiveRecord::Rollback unless result = yield
end
result
end
The state_machine is configured with:
state_machine :state, initial: :uninitialized, use_transactions: false do
Model:
class Recipe < ApplicationRecord
include Redis::Objects
include FriendlyId
Gutentag::ActiveRecord.call self
belongs_to :author, class_name: "Account"
belongs_to :approver, class_name: "Account"
belongs_to :publisher, class_name: "Account"
belongs_to :denier, class_name: "Account"
belongs_to :remover, class_name: "Account"
validates_presence_of :slug
validates_presence_of :ingredients
validates_length_of :ingredients, minimum: 1
validates_presence_of :author
validates_presence_of :created_at
validates_presence_of :updated_at
before_create do
self.author = current_account
end
attr_accessor :current_account
friendly_id :name, :use => [:slugged, :history]
value :queued_at, marshal: true
value :published_at, marshal: true
value :removed_at, marshal: true
state_machine :state, initial: :draft do
event :publish do
transition :draft => :queued
end
event :publish do
transition :draft => :published, if: :allowed_to_autopublish?
end
event :remove do
transition :published => :draft, if: :allowed_to_remove?
end
event :deny do
transition :queued => :draft, if: :allowed_to_deny?
end
event :approve do
transition :queued => :published, if: :allowed_to_approve?
end
before_transition any => :queued do |record|
record.queued_at = Time.zone.now
end
before_transition any => :published do |record|
record.published_at = Time.zone.now
end
before_transition any => :removed do |record|
record.removed_at = Time.zone.now
end
state :queued do
validates_presence_of :queued_at
end
state :removed do
validates_presence_of :removed_at
validates_presence_of :remover
end
state :published do
validates_presence_of :published_at
validates_presence_of :publisher
end
end
private def allowed_to_autopublish?
current_account.verified? || current_account.moderator?
end
private def allowed_to_deny?
current_account.administrator? || current_account.moderator?
end
private def allowed_to_approve?
current_account.administrator? || current_account.moderator?
end
private def allowed_to_remove?
current_account.administrator? || current_account.moderator?
end
end
Resource:
[2] pry(#<Admin::RecipesController>)> resource.save!
ActiveRecord::RecordInvalid: Validation failed: Approver must exist, Publisher must exist, Denier must exist, Remover must exist, Ingredients can't be blank, Ingredients is too short (minimum is 1 character), Created at can't be blank, Updated at can't be blank
I want a relation to only be available to the model when in a certain state:
state_machine :initial do
state :finished do
has_many :clubs
end
...
This doesn't work however, with the following error:
ArgumentError:
Unknown key: :if. Valid keys are: :class_name, :anonymous_class, :foreign_key, :validate, :autosave, :table_name, :before_add, :after_add, :before_remove, :after_remove, :extend, :primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type, :index_errors
# /usr/local/bundle/gems/state_machines-0.4.0/lib/state_machines/assertions.rb:18:in `block in assert_valid_keys'
# /usr/local/bundle/gems/state_machines-0.4.0/lib/state_machines/assertions.rb:16:in `each_key'
# /usr/local/bundle/gems/state_machines-0.4.0/lib/state_machines/assertions.rb:16:in `assert_valid_keys'
# /usr/local/bundle/gems/activerecord-5.0.7.1/lib/active_record/associations/builder/association.rb:78:in `validate_options'
# /usr/local/bundle/gems/activerecord-5.0.7.1/lib/active_record/associations/builder/association.rb:44:in `create_reflection'
# /usr/local/bundle/gems/activerecord-5.0.7.1/lib/active_record/associations/builder/association.rb:29:in `build'
# /usr/local/bundle/gems/activerecord-5.0.7.1/lib/active_record/associations.rb:1371:in `has_many'
# /usr/local/bundle/gems/state_machines-0.4.0/lib/state_machines/state_context.rb:130:in `method_missing'
# ./app/models/owner/base.rb:26:in `block (2 levels) in <class:Base>
...
The if
error, however, doesn't come from my code, as shown above, but from the state_machine code, which introduces an if
condition before calling rails's has_many
.
I'm using rails 5.0, btw.
I started with state_machines, and wrote a few specs about my workflow with state_machines-rspec.
When I decided later to switch to state_machines-activerecord, my transition specs failed, and I can't see why. That kind of spec:
it { is_expected.to transition_from :idle, to_state: :received, on_event: :receive }
generates that kind of error:
Failure/Error:
is_expected.to transition_from :idle, to_state: :received,
on_event: :receive
Expected to be able to transition state from: idle to: received, on_event: receive
which is weird, considering I have this code in my model:
event :receive do
transition idle: :received
end
Is there something I should know about the config of the rspec gem?
(I'm building a Rails 5.1 app)
I have a bunch of states defined with custom values. How can I retrieve the value for a given state? Thanks!
I've switched my Rails 4.1 project from the unmaintained state_machine gem to this one without making any other code changes. I have a model in my application called Order. It's initial state is 'submitted'. Upon calling the following:
Order.submitted
I'm getting the following error:
NoMethodError: undefined method
call' for #Order::ActiveRecord_Relation:0x007ff6b39b8168`
In general, this error appears to be related to this:
http://stackoverflow.com/questions/26413500/undefined-method-call-for-activerecordrelation
But I glanced over the code in this gem, and it appears that the scopes are being defined properly?
If you want to call multiple methods before or after a transaction and specify an array as a key for the do:
entry, for example...
after_transition on: :event, do: [:foo, :bar]
before_transition on: :event, do: [:foo, :bar]
...foo
will be executed, but bar
will not. This does not seem to be th case with an array passed to the on:
entry, for example...
after_transition on: [:event1, :event2], do: :foo
before_transition on: [:event1, :event2], do: :foo
...foo will be called in both cases.
Initial state doesn't work. Its throw validation error state is invalid.
ActiveRecord::RecordInvalid: Validation failed: State is invalid
Now that the state_machines gem has been updated to 0.3.0, any chance for a new release of state_machines-activerecord also?
The docs for this gem say that default :en translations are set, but apparently they are not used in Rails 4.2.1. In a freshly generated Rails project with this gem added, inside a rails console
:
irb(main):003:0> I18n.t!('activerecord.errors.messages.invalid_transition')
I18n::MissingTranslationData: translation missing: en.activerecord.errors.messages.invalid_transition
state machine
1.1 and 1.2, the behaviour of callbacks on ActiveRecord objects was changed. This behaviour has been carried over into the state_machines
gem.Given the following class:
class Vehicle < ActiveRecord::Base
state_machine :state, initial: :parked do
event :drive do
transition :parked => :driving
end
before_transition to: :driving, do: :validate_car_can_drive
end
def validate_car_can_drive
errors.add(:base, "Your car is broken.") if broken?
end
private
def broken?
false
end
end
These tests pass in state_machine 1.1
, but fail in state_machines
and state_machine 1.2
:
context "with a failing callback" do
let(:vehicle) { Vehicle.create }
before(:each) do
allow(vehicle).to receive(:broken?).and_return(true)
end
it "does not update the state" do
expect { vehicle.drive! rescue nil }.not_to change(vehicle, :state)
end
it "raises an error" do
expect { vehicle.drive! }.to raise_error(StateMachine::InvalidTransition)
end
end
No error is raised, and the state is changed.
def validate_car_can_drive
if broken?
errors.add(:base, "Your car is broken.")
false
end
end
I have a model, say Product
, with a belongs_to
relation to Manufacturer
. The Manufacturer Model has a state machine, and now
Manufacturer.with_state(:new)
works, but
product.manufacturer.with_state(:new)
gives NoMethodError: undefined method
with_state'`
For a has_many association I get undefined method
with_state' for #<ActiveRecord::AssociationRelation []`
Note: This worked with the discontinued state_machine gem v.1.2.0
I'm on Rails 4.1.1 and the following behavior seems a bit odd and I'm wondering if its a limitation in the way transitions are done, or possibly a bug(I may also be doing something wrong here)
My Model
class Event < ActiveRecord::Base
before_validation :transition_status, :on => :update
def transition_status
self.status_event = :was_updated
end
state_machine :status, :initial => :new do
event :pend do
transition [:new, :confirmed] => :pending, :unless => :start_date_passed?
end
event :was_updated do
transition [:new, :pending, :confirmed] => :pending
end
event :confirm do
transition :pending => :confirmed
end
end
end
Now some sample code:
@event = Event.first
@event.confirmed? # => true
@event.update_attribute(:start_date => @event.start_date + 1.day)
@event.reload.status # => confirmed
@event.confirmed? # => true
note Assigning using @event.start_date
and then using #save
has the same effect
I expected this to change the status back to pending
, but it never seems to apply the transition when its called(or assigned) in the callback.
My only thought here is that the #around_save
documented here "prevents" the before_transition
from being called and therefore the implicit state change never runs. This is partially supported by the evidence here
At the bottom of this section in the main state machine docs, they say
See each integration's API documentation for more information on the implicit approach.
Searching the entire repo here yields no results for implicit
. I'd be glad to submit a PR with some updated info after I've cleared up my current issue.
I have a model with a conditional validation
validates :nda_accepted,
presence: true,
unless: :draft?
but if I try to transition it fails.
>> Rfq.last.valid?
=> true
>> Rfq.last.delete_draft!
StateMachines::InvalidTransition: Cannot transition state via :delete_draft from :draft (Reason(s): Nda accepted can't be blank)
from /Users/mmoen/code/UnderpantsGnome/britehub-app/vendor/bundle/ruby/2.2.0/gems/state_machines-0.4.0/lib/state_machines/event.rb:224:in `block in add_actions'
Gems
gem 'state_machines', '~> 0.4.0'
gem 'state_machines-activerecord', '~> 0.3.0'
gem 'state_machines-activemodel', '~> 0.3.0'
Simple model looks like this (has status:string column)
class Event < ActiveRecord::Base
state_machine :status, initial: :open do
event :submit do
transition [:open, :rejected] => :submitted
end
event :approve do
transition submitted: :approved
end
event :reject do
transition submitted: :rejected
end
end
end
Trying to change a state, expecting database update
Entry.new.submit
=> true
But nothing gets updated.
It appears that state_machines-activerecord 0.5.1 breaks defining attributes with default value determined by proc.
In 0.5.0, the proc would be evaluated at the instantiation of each object. With state_machines-activerecord 0.5.1, it appears the that proc is evaluated once at class definition time and the value is reused for all objects of that class
Given (in Rails 5.1.6):
class Clip < ApplicationRecord
attribute :uuid, :string, default: -> { SecureRandom.uuid }
end
With state_machines-activerecord 0.5.0:
[1] pry(main)> c1 = Clip.new
=> #<Clip:0x00007ff5e2a720d0
id: nil,
uuid: "0901871e-0d04-409b-b248-7332ce4ad768">
[2] pry(main)> c2 = Clip.new
=> #<Clip:0x00007ff5e1f36360
id: nil,
uuid: "3d130d07-605d-44ea-81a8-3e8991fc4761">
With state_machines-activerecord 0.5.1:
[1] pry(main)> c1 = Clip.new
=> #<Clip:0x00007ff053c98100
id: nil,
uuid: "6d4f5d5e-0ed1-4fd8-99a7-5ca0dd89fd9d">
[2] pry(main)> c2 = Clip.new
=> #<Clip:0x00007ff05441c930
id: nil,
uuid: "6d4f5d5e-0ed1-4fd8-99a7-5ca0dd89fd9d">
I noticed that if I have same validation on multiple states, some of them are not performed...
I will submit testcase
class Product < ActiveRecord::Base
state_machine do
event :delete do
transition any - :deleted => :deleted
end
end
end
Running Product.without_state(:deleted)
produces:
SELECT "products".* FROM "products" WHERE ("products"."state" NOT IN ('deleted'))
This doesn't select records with NULL state
. Using IS DISTINCT FROM 'deleted'
in Postgres selects all values not equal to deleted
including NULLs.
Using v0.5.1 and Postgres 9.6
See issue here: state-machines/state_machines#62
I can see on the internet that others have this too:
https://github.com/gitlabhq/gitlabhq/issues/10445
https://gitlab.com/gitlab-org/gitlab-ce/issues/37361
Should we downgrade state_machines?
I am wanting to benchmark the transition and send to a metric service.. but I can't seem to get the destination state, only the current state.
Hi,
I would love to see the ability to give parameters to transitions, something like:
state_machine :state, initial: :new do
transition :new => :processing, on: :start_processing
transition :processing => :processed, on: :processing_completed
transition :processing => :error, on: :processing_failed do |obj, transition, params|
obj.update_parameters(error => params.first)
end
end
....
my_obj.start_processing!
begin
....
rescue StandardError => e
my_obj.processing_failed(e.message)
end
are there any know issues with Rails 6?
Greetings,
I'm looking for an implementation that supports multiple fsm.
The originating project advertised multiple state machines per object - the current docs don't explicitly say this is the case.
thanks.
Jodi
When I try to run tests using minitest, I get this hard failure that I cannot recover from:
/Users/jon/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:80:in `rescue in block (2 levels) in require': There was an error while trying to load the gem 'state_machines-activerecord'. (Bundler::GemRequireError)
from /Users/jon/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:76:in `block (2 levels) in require'
from /Users/jon/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `each'
from /Users/jon/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `block in require'
from /Users/jon/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `each'
from /Users/jon/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `require'
from /Users/jon/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler.rb:99:in `require'
from /Users/jon/Checkr/checkr/spec/spec_helper.rb:4:in `<top (required)>'
from spec/lib/redis_lock_spec.rb:1:in `require_relative'
from spec/lib/redis_lock_spec.rb:1:in `<top (required)>'
from /Users/jon/.rvm/gems/ruby-2.2.3/gems/m-1.3.4/lib/m/executor.rb:78:in `load'
from /Users/jon/.rvm/gems/ruby-2.2.3/gems/m-1.3.4/lib/m/executor.rb:78:in `suites'
from /Users/jon/.rvm/gems/ruby-2.2.3/gems/m-1.3.4/lib/m/executor.rb:61:in `tests'
from /Users/jon/.rvm/gems/ruby-2.2.3/gems/m-1.3.4/lib/m/executor.rb:15:in `execute'
from /Users/jon/.rvm/gems/ruby-2.2.3/gems/m-1.3.4/lib/m/runner.rb:17:in `run'
from /Users/jon/.rvm/gems/ruby-2.2.3/gems/m-1.3.4/lib/m.rb:13:in `run'
from /Users/jon/.rvm/gems/ruby-2.2.3/gems/m-1.3.4/bin/m:4:in `<top (required)>'
from /Users/jon/.rvm/gems/ruby-2.2.3/bin/m:23:in `load'
from /Users/jon/.rvm/gems/ruby-2.2.3/bin/m:23:in `<main>'
from /Users/jon/.rvm/gems/ruby-2.2.3/bin/ruby_executable_hooks:15:in `eval'
from /Users/jon/.rvm/gems/ruby-2.2.3/bin/ruby_executable_hooks:15:in `<main>'
I am able to run tests fine using ruby directly, but not when using minitest.
Hi,
using ruby-2.2.2, rails 4.1.16.
When i try to call super() in the initialize method i am getting the following error:
ArgumentError:
wrong number of arguments (1 for 0)
Below is the code:
class DefaultWorkflow
include ActiveModel::Dirty
include ActiveModel::Validations
attr_accessor :state, :workflow_type, :workflow_name, :ticket
define_attribute_methods [:state]
def initialize(state = nil, ticket = nil)
@ticket = ticket
super()
end
state_machine :initial => :open do
event :start_progress do
transition [:open, :rework] => :in_progress
end
end
end
Just came across an issue when upgrading an app from rails 4.2 to rails 5.0.
ActiveRecord::Base has an arity of 2 but the new method defined in define_state_initializer only has an arity of 1. An error is thrown when super is called from a descendent that uses the options argument a
ArgumentError "wrong number of arguments (given 2, expected 0..1)"
is thrown.
Thanks
How do you test this with rspec. can't find any doc.
I know it is fairly obvious, but I think it would be a useful note
Guys, i dont know if this is my mistake or real bug.
someone can help me?
When i use dynamic approach, i geting one problem:
the state dont persisted on database.
i reproduce the issue in below repo
https://github.com/thiagoliof/testFlow
tks for all
In an existing model, my state column is a Rails enum and using state_machine on this column generates some warnings (and probably does not work) :
Instance method "processing?" is already defined in #<Module:0x00000007615c68>, use generic helper instead or set StateMachines::Machine.ignore_method_conflicts = true.
Both Enrollment and its :state machine have defined a different default for "state". Use only one or the other for defining defaults to avoid unexpected behaviors.
I am migrating from aasm and this is a nice feature I miss.
Will 0.4.0 stable be released to RubyGems any time soon? Would be nice for Rails 5 support.
Hello,
Quick question: Do the gem authors know if this gem will work with Rails 4.0? Is there a reason AR 4.1 is the lowest AR version?
I'm currently supporting a Rails 4.0 application, and I don't want to upgrade the application to Rails 4.1 just to try out this gem. I'd rather see if this gem could work with Rails 4.0 first. Its also a bummer that the old state_machine gem doesn't support Rails 4.0 and this gem starts at 4.1. Seems like a blind spot to me.
Hi! I've noticed that callbacks for implicit event transitions don't work.
Example:
state_machine :state, initial: :profile_details do
event :pending do
transition from: all - [:pending, :approved, :rejected], to: :pending
end
after_transition on: :pending, do: :generate_something
and now
profile.pending
profile.reload.something != nil # => true
but
profile.state = 'pending'
profile.save
profile.reload.something # => nil
Is there any solution to enable callbacks using normal assignment of the data (without using events)?
Gems:
Rails 5.0
state_machines-activerecord 0.4.0
In db/schema.rb
:
t.string "state", default: "active", null: false
I would expect that: Foo.new.state
to be active
. But without setting initial: :active
in the state machine definition, it sets the value to nil
.
edit: using v0.5.1
The content of this page (http://www.rubydoc.info/github/state-machines/state_machines-activerecord/StateMachines/Integrations/ActiveRecord) is very important to developers, such as callback ordering.
I am wondering if we can have the readme link to this page, or better yet, move this documentation back into the readme.
Hi all,
In Spree I have enabled transactions for the order state machine. Now with inventory units, whenever one is saved, the around_save block gets called and saves it again. It is quite strange, but I end up with 2 inventory_units with I only needed one. Have any of you seen anything similar?
I have a controller that performs a search. To do that I have a lot of scopes chained together to obtain the right result. Because the user doesn't need to fill all scopes, when a scope is not used, the scope must be transparent.
Usually, I do for example scope :in_range, ->(min, max) { where(id: (min..max)) if min.present? && max.present? }
used like that:
Project.in_range(params[:min], params[:max)
.in_country(params[:country])
.with_job(params.dig(:job, :name), params.dig(:job, :user))
what do you think if I modify
state_machines-activerecord/lib/state_machines/integrations/active_record.rb
Lines 567 to 569 in daec4b5
def create_scope(name, scope)
lambda { |model, values| model.where(scope.call(values)) if values.present? }
end
So I will change the behaviour from:
$> Project.with_states(nil).to_sql
IndexError: nil is an invalid name
to:
$> Project.with_states(nil).to_sql
=> "SELECT \"projects\".* FROM \"projects\""
say if I have the following associations
class User < ApplicationRecord
has_many :active_projects, -> { with_state(:active) }, class_name: Project
end
class Project < ApplicationRecord
belongs_to :user
state_machine :state, initial: :pending do
state :active
end
end
And if I do the following query
> Project.joins(user: :active_projects).to_sql
=> "SELECT `projects`.* FROM `projects` INNER JOIN `users` ON `users`.`id` = `projects`.`user_id` INNER JOIN `projects` `active_projects_users` ON `active_projects_users`.`user_id` = `users`.`id` AND (`projects`.`state` IN ('active'))"
I'm getting this warning after trigger an state machine event:
DEPRECATION WARNING: `serialized_attributes` is deprecated without replacement, and will be removed in Rails 5.0.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.