aasm undefined method`state'

时间:2018-03-18 18:56:52

标签: ruby-on-rails ruby-on-rails-5 state-machine aasm

我正在配置我的rails 5.1.4模型以通过aasm支持状态,我遇到了问题,显然它没有初始化方法{{1}对于模型。当我打电话给state时似乎使用了这个,所以打破了我的模型。其他方法似乎工作正常。

我像这样配置(并运行)了我的迁移:

item.save

并在item.rb模型文件中配置它:

add_column :item, :aasm_state, :string
我在rails控制台中输入

class Item
  include AASM
  [...]
  aasm do
    state :unpublished, initial: true
    state :published
    state :blocked

    event :publish do
      transitions from: :unpublished, to: :published
    end

    event :unpublish do
      transitions from: :published, to: :unpublished
    end

    event :block do
      transitions from: :published, to: :blocked
    end

    event :unblock do
      transitions from: :blocked, to: :published
    end
  end
  [...]
end

更新 添加完整的堆栈跟踪:

> item = Item.new
  => #<Item id: nil, title: nil, description: nil, created_at: nil, updated_at: nil, aasm_state: "unpublished">
> item.aasm_statenike
  => "unpublished"
> item.aasm.states.map(&:name)
  => [:unpublished, :published, :blocked]
> item.state #<===== WHERE IS STATE?
NoMethodError: undefined method `state' for #<Item:0x007f8d43263810>
  from (irb):2
> item.save
NoMethodError: undefined method `state' for #<Item:0x007f8d4a30f550>
  Did you mean?  state=
    from (irb):3

> item.publish
  => true
> item.aasm_state
  => "published"
> item.state #<===== WHERE IS STATE?
NoMethodError: undefined method `state' for #<Item:0x007f8d43263810>
  from (irb):9

1 个答案:

答案 0 :(得分:0)

默认情况下,AASM不会在您的模型上创建名为state的方法。 它曾经多年前使用......但是当我们的模型已经有一个名为state的列时(例如,当它是一个地址模型时)出现了问题。

如果要访问模型的当前状态,则需要使用AASM方法current_state,如下所示:

item.aasm.current_state

aasm doco here

中的更多内容