如何从使用state_machine转移到assm? Rails App

时间:2015-07-18 04:53:31

标签: ruby-on-rails ruby

我使用state_machine gem编写了这段代码但是如何使用assm gem创建等效代码?

 state_machine :state, initial: :pending do
        after_transition on: :accept, do: :send_acceptance_email

        state :requested

        event :accept do
            transition any => :accepted
        end
    end

这是在接受友谊请求后完成的事情

def self.request(user1, user2)
      transaction do
        friendship1 = create!(user: user1, friend: user2, state: 'pending')
        friendship2 = create!(user: user1, friend: user2, state: 'requested')

        friendship1.send_request_email
        friendship1

      end
    end


    def send_request_email
        UserNotifier.friend_requested(id).deliver
    end

    def send_acceptance_email
        UserNotifier.friend_accepted(id).deliver 
    end

User.rb

has_many :friends, through: :user_friendships,
                       conditions: { user_friendships: { state: 'accepted' } }

    has_many :pending_user_friendships, class_name: 'UserFriendship',
                                        foreign_key: :user_id,
                                        conditions: { state: 'pending' }

    has_many :pending_friends, through: :pending_user_friendships, source: :friend

1 个答案:

答案 0 :(得分:0)

您需要在模型中包含此行

include AASM

#though虽然我总是使用status作为状态机的列,但你也可以尝试使用state作为列。希望这不是一个问题。

aasm column: 'state', initial: :pending, whiny_transitions: true do
  state :requested # im not seeing any event which set this state
  state :accepted

  #if you want an to trigger request event from any state simply add this
  event :request,   after: Proc.new { send_request_email }       do transitions to: :requested end


  #if you want to trigger accepted state from any state do this
  event :accept,   after: Proc.new { send_acceptance_email }       do transitions to: :accepted end

  #if you want to trigger accepted state from only requeste state
  event :accept,   after: Proc.new { send_acceptance_email }      do transitions from: :requested,   to: :accepted  end

end

如果您不喜欢异常并且喜欢简单的真假作为回应,请告诉AASM不要发牢骚:

:whiny_transitions => false

参考:https://github.com/aasm/aasm