Can somebody give an active record example for pluginaweek - statemachine?

自作多情 提交于 2019-12-07 11:14:51

问题


Can somebody give a simple example on howto use pluginaweek state_machine for a ticket model with active record? I do not understand the complex examples from the docs.

Example states:

  • new -> accepted, declined, feedback
  • accepted -> solved or feedback
  • feedback -> accepted or solved

回答1:


Example ticket model (not tested)

class Ticket < ActiveRecord::Base
  attr_accessible :name, :description
  attr_accessible :state_event
  validates :name, :presence => true

  state_machine :initial => :new do

    event :accept do 
      transition [:new, :feedback] => :accepted
    end

    event :decline do
      transition :new => :declined
    end

    event :feedback do
      transition [:new, :accepted] => :feedbacked
    end

    event :solve do
      transition [:accepted, :feedback] => :solved
    end
  end
end

Get all possible transitions in form

<%= f.collection_select :state_event, @ticket.state_transitions, :event, :human_to_name, :include_blank => @ticket.human_state_name %>

Get state of ticket: <%= ticket.state %>

Get all possible ticket transitions as links:

<% ticket.state_transitions.each do |transition| %>
    <%= link_to transition.event, ticket_path(ticket, ticket: {:state_event => transition.event}), :method => :put %>
<% end %>

List all possible transitions to filter in controller

<ul>
  <li class="<%= 'active' if params[:state].blank? %>"><%= link_to 'All', tickets_path %></li>
  <% Ticket.state_machine.states.each do |state| %>
    <li class="<%= 'active' if params[:state] == state.name.to_s  %>">
      <%= link_to state.name, tickets_path(:state => state.name) %>
    </li>
  <% end %>
</ul>

class TicketsController extends ApplicationController
  ...
  def index
    @tickets = Ticket.where("state = ?", params[:state])
    ...       


来源:https://stackoverflow.com/questions/9559702/can-somebody-give-an-active-record-example-for-pluginaweek-statemachine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!