LogofaT
LogofaT

Reputation: 289

Rails dissabling user

I'm working on project were users can log in and users can be disabled, user states are changed via state_machine and user managing is realized using Devise. My problem is that users can disable themselves. I should add a condition to the state change something like:

transition :enabled => :disabled, :disabled => :enabled, if: :not_self_disabling

not_self_disabling is a method in the User class; the only problem is that current_user is not known in model, and also accessing session is ugly, as it violates MVC's separation of concerns. Any suggestions?

Upvotes: 0

Views: 39

Answers (1)

Jacob Brown
Jacob Brown

Reputation: 7561

Without seeing your code, it's hard to tell whether this really is the best way to set up user disabling. It may just be better to protect against self-disabling in the controller. However, you can do something like (untested):

event :toggle_user_status do
  transition :enabled => :disabled, :disabled => :enabled
end

def toggle_user_status(current_user, *args)
  super unless current_user == self
  # Note: it may be necessary (or better) to do `super(*args)`, 
  # since state_machine doesn't need to know about your `current_user`
end

And then pass in your current_user to the toggle_user_status method. Overriding event methods is described in the RDoc here: http://rubydoc.info/github/pluginaweek/state_machine/StateMachine/Machine:event.

Upvotes: 1

Related Questions