Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Clarification on state_machine

Hope everybody is having a good weekend so far -

After re-watching the ruby rapids videos on adding state machine I don't quite understand how the transitions and events work. The documentation on github wasn't easy reading right off the bat.

  • What's the difference between transitions and events?
  • How do you trigger a change in state`?

For examples sake I'll add a state to statuses, and have it transition from 'unread' to 'read' when viewed in statuses#show

So...

$ rails generate migration add_state_to_statuses

Now prepping the migration:

class AddStateToStatuses < ActiveRecord::Migration def change add_column :statuses, :state, :string add_index :statuses, :state end end

Raking the db:

$ rake db:migrate

Adding state_machine to the model:

state_machine initial: :unread do
end

At this point when a status is created the state field in the db will be filled with 'unread'. Now just a trigger when (anybody - doesn't matter for the example) hits statuses#show and the actual state change?

2 Answers

Jason Seifer
STAFF
Jason Seifer
Treehouse Guest Teacher

Hey Zander,

Thanks a lot for the feedback, we'll try making the state machine lessons more descriptive.

The difference between a transition and an event is that a transition is the process of going from one state to another. An event is the thing that triggers it.

In order to convert the state to unread, you'll need to make a specific state for it in your model. Then you can create, for example, a "mark_read" event. You could then update other fields or perform actions on that if you wanted to. You'd probably want to do that in the controller.

Thanks Jason, that actually makes a lot more sense. The lesson is great at showing what state machine does, there's just a bunch of methods flying around in there.