接手了一个 Rails 升级的项目。本人算是 Rails 小白。想请教大家 Rails 版本 4.2 --> 5.2 Ruby 2.3
我有一个 Recommendation model,其中包含和另一个 model WorkflowSate 的 association 代码如下
class Recommendation < ActiveRecord::Base
belongs_to :state, class_name: 'WorkflowState', foreign_key: :workflow_state_id
class WorkflowState < ApplicationRecord
WORKFLOW_STATES = ['DRAFT',
'PENDING_APPROVAL',
'APPROVED']
def self.state_enums
hash = {}
WorkflowState.distinct.each do |state|
hash[state.to_sym] = state.id
end
hash
end
同时有一个 Recommendation 的 state machine
module RecommendationStateMachine
# state setting
def self.included(klass)
klass.send(:include, AASM)
klass.enum workflow_state_id: WorkflowState.state_enums
# States
klass.aasm column: :workflow_state_id, enum: true do
state :draft, initial: true
state :pending_approval
state :approved
升级之前一切功能如常,rails console 中查看 Recommendation:
r = Recommendation.first
=> #<Recommendation id: 120463, workflow_state_id: 3>
升级后查看 rails console
r = Recommendation.first
=> #<Recommendation id: 120463, workflow_state_id: "apprvoed">
因为值的变化,导致 Recommendation 中的 belongs_to 找不到对应的 workflow state。所以 test 报错。 ROR 新手,有点摸不着头脑,不知道为什么会发生 enum 值发生变化的情况。求大佬帮助