简体   繁体   中英

rails state_machine button transition

newbie question I'm afraid regarding the state_machine gem.

I have set up a class as follows

class Idea < ActiveRecord::Base

  #state machine
  state_machine :state, :initial => :voting_underway do

    event :progress do
        transition :voting_underway => :accepted, :accepted => :in_development, :in_development => :done
    end

    event :reject do
        transition all => :rejected
    end

    def initialize
      super() # NOTE: This *must* be called, otherwise states won't get initialized
    end
  end
end

Here comes the silly question. How do I "Progress" an idea from, for example, the HAML show page for that idea. How would you configure the button?

First some general pointers:

It doesn't make much sense to have the initialize method in the state_machine block. And you don't need it at all unless you want to do something custom in it, which you typically don't.

That said, there are many ways to do what you want, but I would go for a custom controller action.

Create a custom action in your routes and in your IdeasController:

# routes.rb

resources :ideas do
  put "progress"
end

# ideas_controller.rb

def progress
  @idea = Idea.find(params[:id])
  @idea.progress!
end

# in a view

= link_to "Transition", idea_progress_path, method: :put

You could also to a put request to your existing update action and set the state_event parameter (given that your state machine attribute is named state) to whatever event you'd like to fire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM