gpt4 book ai didi

ruby-on-rails - Rails 枚举验证不起作用但引发 ArgumentError

转载 作者:行者123 更新时间:2023-12-04 23:17:12 25 4
gpt4 key购买 nike

创建了一个线程 here ,但这并不能解决我的问题。

我的代码是:

course.rb

class Course < ApplicationRecord
COURSE_TYPES = %i( trial limited unlimited )
enum course_type: COURSE_TYPES
validates_inclusion_of :course_type, in: COURSE_TYPES
end

course_controller.rb
class CoursesController < ApiController
def create
course = Course.new(course_params) # <-- Exception here
if course.save # <-- But I expect the process can go here
render json: course, status: :ok
else
render json: {error: 'Failed to create course'}, status: :unprocessable_entity
end
end

private
def course_params
params.require(:course).permit(:course_type)
end
end

我的测试用例:

course_controller_spec.rb
describe '#create' do
context 'when invalid course type' do
let(:params) { { course_type: 'english' } }
before { post :create, params: { course: params } }

it 'returns 422' do
expect(response.status).to eq(422)
end
end
end

运行上述测试用例时,我得到了 ArgumentError Rails issues 中描述的异常

所以我希望如果我设置一个无效的 course_type枚举,它将 在验证阶段失败而不是引发异常 .

此外,我知道在 here 的 rails 钩子(Hook)下到底发生了什么。而我 不想手动抢救在每个分配枚举类型值的代码块中都会出现这种异常!

对此有何建议?

最佳答案

我找到了解决方案。我自己在 Rails 6 中测试过。

# app/models/contact.rb
class Contact < ApplicationRecord
include LiberalEnum

enum kind: {
phone: 'phone', skype: 'skype', whatsapp: 'whatsapp'
}

liberal_enum :kind

validates :kind, presence: true, inclusion: { in: kinds.values }
end

# app/models/concerns/liberal_enum.rb
module LiberalEnum
extend ActiveSupport::Concern

class_methods do
def liberal_enum(attribute)
decorate_attribute_type(attribute, :enum) do |subtype|
LiberalEnumType.new(attribute, public_send(attribute.to_s.pluralize), subtype)
end
end
end
end

# app/types/liberal_enum_type.rb
class LiberalEnumType < ActiveRecord::Enum::EnumType
# suppress <ArgumentError>
# returns a value to be able to use +inclusion+ validation
def assert_valid_value(value)
value
end
end

用法:

contact = Contact.new(kind: 'foo')
contact.valid? #=> false
contact.errors.full_messages #=> ["Kind is not included in the list"]

关于ruby-on-rails - Rails 枚举验证不起作用但引发 ArgumentError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37177893/

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