pluginaweek / state_machine

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

State doesn't persist on duplicated object after reloading #338

Closed davidcpell closed 9 years ago

davidcpell commented 9 years ago

I'm finding that duplicated ActiveRecord objects are ending up with a state of nil after being saved and reloaded.

class Job < ActiveRecord::Base
...
state_machine :state, initial: :posted do
...
end

# job_duplicator.rb
class JobDuplicator
  def self.duplicate(job)
    new_job = job.dup
    new_job.assign_attributes(
        state: "posted",   
        discount_code_id: nil,
        credit_applied: 0
        )
    new_job
  end
end
class Admin::JobsController < AdminController
  ... 
  def duplicate
    @job = Job.find(params[:id])
    @new_job = JobDuplicator.duplicate(@job)
     if @new_job.save
        redirect_to edit_admins_job_path(@new_job), notice: "Successfully duplicated #{@job.to_s} as #{@new_job.to_s}. You can edit the details below, if you'd like."
    else
        redirect_to :back, alert: "There was a problem duplicating #{@job.to_s}."
    end
  end
...
end

The above redirect takes place but I immediately get a nilClass error on the view because state is now nil for some reason. Here is the same behavior in the Rails console:

[1] pry(main)> j = Job.first
[2] pry(main)> k = JobDuplicator.duplicate(j)
[3] pry(main)> k.state => "posted"
[4] pry(main)> k.save
[5] pry(main)> k.new_record? => false
[6] pry(main)> k.state => "posted"
[7] pry(main)> k.reload
[8] pry(main)> k.state => nil

Not sure if this a state_machine problem or something I'm not understanding about Ruby/ActiveRecord, but I haven't seen behavior like this before.

Rails 4.2 state_machine 1.2, remote: git://github.com/seuros/state_machine.git

seuros commented 9 years ago

@davidcpell could you try with state-machines-activerecord ? we fixed some bugs there.

davidcpell commented 9 years ago

@seuros sure!

davidcpell commented 9 years ago

thanks @seuros, state-machines-activerecord is not exhibiting the problem!