在状态机转换后发送电子邮件

时间:2014-08-13 12:09:27

标签: ruby-on-rails

我正在尝试使用Rails 4.1构建一个小费用跟踪应用。当用户提交费用请求时,默认情况下将其状态标记为待处理。管理员必须批准该请求。我使用state_machine gem来做到这一点。

我想在批准或拒绝请求后发送电子邮件,我尝试了以下模型方法:

state_machine initial: :pending do
        state :pending
        state :approved
        state :rejected
        #after_transition :on => :approved do |expense, transition|
            #expense.send_expense_approved_email
        #end

        #after_transition :on => :rejected do |expense, transition|
            #expense.send_expense_approved_email
        #end
         after_transition :on => :approved, :do => :send_expense_approved_email
         after_transition :on => :rejected, :do => :send_expense_declined_email


        event :approved do
            transition [:pending, :rejected] => :approved
        end

        event :rejected do
            transition [:pending, :approved] => :rejected
        end
    end

    def expense_amount
        items.to_a.sum { |item| item.amount }
    end

    def send_expense_approved_email
        ExpenseMailer.expense_approved(expense).deliver
    end

    def send_expense_declined_email
        ExpenseMailer.expense_declined(expense).deliver
    end
end

状态转换成功后,我无法触发电子邮件。我已经在控制器操作中测试了邮件程序,它们被发送出去了。我如何让它工作?

1 个答案:

答案 0 :(得分:0)

这些模型方法不起作用。因此,使用if和else语句检查状态,然后在更新操作中触发电子邮件。不确定,如果这是Rails方式,但是,它正在发挥作用。