Skip to content

Instantly share code, notes, and snippets.

@dinnouti
Created June 6, 2013 11:42
Show Gist options
  • Save dinnouti/5720934 to your computer and use it in GitHub Desktop.
Save dinnouti/5720934 to your computer and use it in GitHub Desktop.
Adding state_machine events to link_to
enable: <%= link_to 'Enable', user_update_state_path(user.id, state_event: 'register', access_state_event: 'enable') %><br>
disable: <%= link_to 'disable', user_update_state_path(user.id, state_event: 'unregister', access_state_event: 'disable') %>
State::Application.routes.draw do
resources :users do
get :update_state
end
ActiveRecord::Schema.define(:version => 20130606103331) do
create_table "users", :force => true do |t|
t.string "name"
t.string "state"
t.string "access_state"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
end
class User < ActiveRecord::Base
attr_accessible :access_state, :name, :state, :state_event, :access_state_event
validates_presence_of :name, :state, :access_state
state_machine :initial => :unregistered do
event :register do
transition :unregistered => :registered
end
event :unregister do
transition :registered => :unregistered
end
end
state_machine :access_state, :initial => :enabled do
event :enable do
transition all => :enabled
end
event :disable do
transition all => :disabled
end
end
end
def update_state
#render :text => params.inspect
logger.info params.to_yaml
@user = User.find(params[:user_id])
@user.access_state_event = params[:access_state_event]
@user.state_event = params[:state_event]
respond_to do |format|
if @user.save
format.html { redirect_to users_path, notice: 'User was successfully updated.' }
else
format.html { redirect_to users_path, notice: 'System error [user.update_state].' }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment