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:
I'm finding that duplicated ActiveRecord objects are ending up with a
state
ofnil
after being saved and reloaded.The above redirect takes place but I immediately get a
nilClass
error on the view becausestate
is nownil
for some reason. Here is the same behavior in the Rails console: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