Rails在模型中未定义的方法

时间:2014-11-28 12:57:13

标签: ruby-on-rails ruby-on-rails-4 transactions state-machine

不知何故,这个让我感到困惑,一切都在那里,但不知何故它不起作用:

self.status_transition.update中的任何一个都不起作用

  require 'state_machine/core'
  class V1::Order < ActiveRecord::Base
  extend StateMachine::MacroMethods

  has_one :status_transition
  after_create :create_status

  def create_status
    self.create_status_transition if self.status_transition.nil?
  end
    state_machine initial: :draft do
    state :draft, value: 0
    state :placed, value: 1
    state :paid, value: 2
    state :canceled, value: 3

    after_transition any => any do |t|
      self.status_transition.update(event: t.event, 
       from: t.from, to: t.to)
      #self.status_transition.update(event: "dsa", from: "ds", to: "dsd")


    end

    event :place do 
      transition :draft => :placed
    end

错误:

2.1.1 :004 > o.place
  (0.1ms)  begin transaction
  SQL (0.9ms)  UPDATE "v1_orders" SET "state" = ?, "updated_at" = ? WHERE "v1_orders"."id" = 19
  [["state", 1], ["updated_at", "2014-11-28 12:48:40.256820"]]
  (91.7ms)  rollback transaction
  NoMethodError: undefined method `status_transition' for #<StateMachine::Machine:0x00000107aa78e8>

o = V1::Order.create # => #<V1::Order id: 22, state: 1, user_id: nil, created_at: "2014-11-28 13:29:03", updated_at: "2014-11-28 13:29:03", vat: #<BigDecimal
:101c09fe8,'0.2E2',9(18)>> 

o.status_transitions # IS CREATED

o.status_transition # => #<V1::StatusTransition id: 23, event: nil, from: nil, to: nil, order_id: 28, created_at: "2014-11-28 13:25:55", updated_at: "2014-1
1-28 13:25:55"> 

o.place会返回上述错误。

1 个答案:

答案 0 :(得分:1)

根据documentation块shell将:do键的值传递给::after_transition回调,因此:

class V1::Order
 after_transition any => any do |order, transition|
   p order # disable this as needed
   order.status_transition.update(event: transition.event, from: transition.from, to: transition.to)
 end
end