gpt4 book ai didi

ruby-on-rails - AASM 不适用于我的 rails 3 和 ruby​​ 1.8.7(未定义方法 `name' 为 nil :NilClass )

转载 作者:数据小太阳 更新时间:2023-10-29 06:54:21 30 4
gpt4 key购买 nike

我正在使用 Rails 3.2.2,带有 aasm gem,我有这样的 Document 模型:

class Document < ActiveRecord::Base
include AASM

aasm do
state :unread, :initial => true
state :read
state :closed

event :view do
transitions :to => :read, :from => [:unread]
end

event :close do
transitions :to => :closed, :from => [:read, :unread]
end
end

现在在我的控制台上:

➜  ✗ bundle exec rails c
Loading development environment (Rails 3.2.2)
irb(main):006:0> Document.create!(:title => 'test')
(0.2ms) BEGIN
SQL (0.3ms) INSERT INTO `documents` (`aasm_state`, `checklist_id`, `created_at`, `description`, `dir`, `planned_date`, `procedure_id`, `section`, `subsection`, `title`, `updated_at`) VALUES (0, NULL, '2012-06-16 20:03:18', NULL, NULL, NULL, NULL, NULL, NULL, 'test', '2012-06-16 20:03:18')
(0.4ms) COMMIT
=> #<Document id: 28, title: "test", description: nil, dir: nil, section: nil, subsection: nil, planned_date: nil, procedure_id: nil, checklist_id: nil, created_at: "2012-06-16 20:03:18", updated_at: "2012-06-16 20:03:18", aasm_state: 0>
irb(main):007:0> doc = Document.last
Document Load (0.3ms) SELECT `documents`.* FROM `documents` ORDER BY `documents`.`id` DESC LIMIT 1
=> #<Document id: 28, title: "test", description: nil, dir: nil, section: nil, subsection: nil, planned_date: nil, procedure_id: nil, checklist_id: nil, created_at: "2012-06-16 20:03:18", updated_at: "2012-06-16 20:03:18", aasm_state: 0>
irb(main):008:0> doc.view!
NoMethodError: undefined method `name' for nil:NilClass
from /Library/Ruby/Gems/1.8/gems/aasm-3.0.6/lib/aasm/supporting_classes/state.rb:15:in `=='
from /Library/Ruby/Gems/1.8/gems/aasm-3.0.6/lib/aasm/aasm.rb:143:in `aasm_state_object_for_state'
from (irb):8:in `find'
from /Library/Ruby/Gems/1.8/gems/aasm-3.0.6/lib/aasm/aasm.rb:143:in `each'
from /Library/Ruby/Gems/1.8/gems/aasm-3.0.6/lib/aasm/aasm.rb:143:in `find'
from /Library/Ruby/Gems/1.8/gems/aasm-3.0.6/lib/aasm/aasm.rb:143:in `aasm_state_object_for_state'
from /Library/Ruby/Gems/1.8/gems/aasm-3.0.6/lib/aasm/aasm.rb:158:in `aasm_fire_event'
from /Library/Ruby/Gems/1.8/gems/aasm-3.0.6/lib/aasm/base.rb:48:in `view!'
from (irb):8

如你所见,我不断得到

undefined method `name' for nil:NilClass

我正在使用 Ruby 1.8.7。

最佳答案

我刚刚遇到了同样的问题。它的出现是因为默认情况下状态变量是 nil 而不是被设置为初始状态。要解决此问题,在您的情况下,您需要在模型上添加一个访问器,如下所示:

def aasm_state
self[:aasm_state] || "unread"
end

关于ruby-on-rails - AASM 不适用于我的 rails 3 和 ruby​​ 1.8.7(未定义方法 `name' 为 nil :NilClass ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11066659/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com