I’m implementing pluginaweek’s state_machine gem. I narrowed the code down to just this so I can understand the problem more easily. Let’s assume I only have one status for now:
class Event < ActiveRecord::Base
state_machine :status, :initial => :active_offer do
end
def status
'Active Offer'
end
end
The error I’m getting when creating new Event objects either via seeding or via the browser is {:status=>["is invalid"]}.
The plan is to include a condition for all the different statuses and return a custom string to the view. The entire project’s views currently use the .status syntax so I’m trying to smoothly install this. I started this solution based on reading the api docs:
http://api.rubyonrails.org/classes/ActiveRecord/Base.html#label-Overwriting+default+accessors
This is my main goal:
def status
if read_attribute(:status) == 'active_offer' && self.start_date > Time.now
'Active Offer'
elsif read_attribute(:status) == 'active_offer' && self.start_date < Time.now
'Expired'
else read_attribute(:status) == 'cancelled'
'Cancelled'
end
end
What can I do to make the state_machine block use the normal accessor so it gets the database value?
THE SILVER BULLET SOLUTION:
My main problem was the accessor override status. When state_machine code was running, it was reading the current status through my accessor override and therefore getting a custom string returned, which was an invalid status. I had to make state_machine use :state. I didn’t do this originally because I already had a :state attr for provinces and such, so I migrated that to :address_state.
Pretty sure you just need to change the definition’s name:
EDIT:
If I understand you correctly, which I’m not certain I do, this will work:
Then you can do your
if...statements, etc., in the controller or something, and transition them with something like@event.expireorif @event.expired. If you want it automated you’ll need something like whenever.