gpt4 book ai didi

ruby-on-rails - 迁移期间的 Ruby 工作流问题

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:56 26 4
gpt4 key购买 nike

我在使用 Gem 的 ActiveRecords 中使用 Ruby Workflow:Workflow

现有运行代码包含:

  • 我有一个 ActiveRecord:X
  • 我已经进行了两次迁移:
    • (Ref1) CreateX 迁移(创建表 X)
    • (Ref2) CreateInitialEntryInX 迁移(在表 X 中创建一个条目)

新变化:

  • 现在我想在 ActiveRecord X 中添加工作流,因此我做了:
    • (Ref3) 我在 ActiveRecord Model X 中添加了工作流代码(提及 :status 作为我的工作流字段)
    • (Ref4) AddStatusFieldToX 迁移(在表 X 中添加 :status 字段)

现在,当我在更改后运行 rake db:migrate 时,(Ref2) 会中断,因为 Migration 会查找 :status 字段,因为它在 ActiveRecord 模型中的工作流部分中提到,但是 :status 字段尚未添加,因为迁移 (Ref4) 尚未执行。

因此,当所有迁移按顺序运行时,所有构建都会失败,对此有什么解决方案吗?我不想重新排序任何迁移或编辑任何旧的现有迁移。

我的模型看起来像:

  class BaseModel < ActiveRecord::Base
#
# Workflow to define states of Role
#
# Initial State => Active
#
# # State Diagram::
# Active --soft_delete--> Deleted
# Deleted
#
# * activate, soft_delete are the event which triggers the state transition
#
include Workflow
workflow_column :status
workflow do
state :active, X_MODEL_STATES::ACTIVE do
event :soft_delete, transitions_to: :deleted
end
state :deleted, X_MODEL_STATES::DELETED

on_transition do |from, to, event, *event_args|
self.update_attribute(:status, to)
end
end

def trigger_event(event)
begin
case event.to_i
when X_MODEL_EVENTS::ACTIVATE
self.activate!
when X_MODEL_EVENTS::SOFT_DELETE
self.soft_delete!
end
rescue ....
end
end

class X_MODEL_STATES
ACTIVE = 1
DELETED = 2
end

class X_MODEL_EVENTS
ACTIVATE = 1
SOFT_DELETE = 2
end

# Migrations(posting Up functions only - in correct sequence)
#--------------------------------------------------

#1st: Migration - This is already existing migration
CreateX < ActiveRecord::Migration
def up
create_table :xs do |t|
t.string :name
t.timestamps null: false
end
end
end

#2nd: Migration - This is already existing migration
CreateInitialX < ActiveRecord::Migration
def up
X.create({:name => 'Kartik'})
end
end

#3rd: Migration - This is a new migration
AddStatusToX < ActiveRecord::Migration
def up
add_column :xs, :status, :integer
x.all.each do |x_instance|
x.status = X_MODEL_STATES::ACTIVE
x.save!
end
end
end

因此,当 Migration#2 运行时,它会尝试查找要写入的 :status 字段的初始值为 X_MODEL_STATES::ACTIVE,正如 Active Record 中提到的那样将文件工作流程建模为:workflow_column :status 并且未找到该字段,因为 Migration#3 尚未执行。

最佳答案

您可以通过检查 column_name 来结束您的工作流代码。

if self.attribute_names.include?('status')
include Workflow
workflow_column :status
workflow do
...
end
end

这将导致仅在“AddStatusToTable”迁移成功运行后才运行工作流代码。

关于ruby-on-rails - 迁移期间的 Ruby 工作流问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38101585/

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