我是rails新手。我使用以下class User
及其class Teacher < User
子类创建 STI。当我填写用户表单时,它抛出了一个错误。
名称错误在/users
未初始化的常量 用户::教师
app/controllers/users_controller.rb,第 29 行
24 end
25
26 # POST /users
27 def create
28 byebug
> 29 @user = User.new(user_params)
30 authorize @user
31 if @user.save
32 render json: @user, status: :created, location: @user, serializer: UserSerializer
33 else
34 render json: @user.errors, status: :unprocessable_entity
应用回溯
- app/controllers/users_controller.rb:29:in 'create'
完整回溯
activerecord (6.0.1) lib/active_record/inheritance.rb:206:in `compute_type'
activerecord (6.0.1) lib/active_record/inheritance.rb:233:in `find_sti_class'
activerecord (6.0.1) lib/active_record/inheritance.rb:263:in `subclass_from_attributes'
activerecord (6.0.1) lib/active_record/inheritance.rb:56:in `new'
app/controllers/users_controller.rb:29:in `create'
actionpack (6.0.1) lib/action_controller/metal/basic_implicit_render.rb:6:in `send_action'
actionpack (6.0.1) lib/abstract_controller/base.rb:196:in `process_action'
actionpack (6.0.1) lib/action_controller/metal/rendering.rb:30:in `process_action'
actionpack (6.0.1) lib/abstract_controller/callbacks.rb:42:in `block in process_action'
activesupport (6.0.1) lib/active_support/callbacks.rb:135:in `run_callbacks'
actionpack (6.0.1) lib/abstract_controller/callbacks.rb:41:in `process_action'
actionpack (6.0.1) lib/action_controller/metal/rescue.rb:22:in `process_action'
actionpack (6.0.1) lib/action_controller/metal/instrumentation.rb:33:in `block in process_action'
activesupport (6.0.1) lib/active_support/notifications.rb:180:in `block in instrument'
activesupport (6.0.1) lib/active_support/notifications/instrumenter.rb:24:in `instrument'
activesupport (6.0.1) lib/active_support/notifications.rb:180:in `instrument'
actionpack (6.0.1) lib/action_controller/metal/instrumentation.rb:32:in `process_action'
actionpack (6.0.1) lib/action_controller/metal/params_wrapper.rb:245:in `process_action'
activerecord (6.0.1) lib/active_record/railties/controller_runtime.rb:27:in `process_action'
actionpack (6.0.1) lib/abstract_controller/base.rb:136:in `process'
actionpack (6.0.1) lib/action_controller/metal.rb:191:in `dispatch'
actionpack (6.0.1) lib/action_controller/metal.rb:252:in `dispatch'
actionpack (6.0.1) lib/action_dispatch/routing/route_set.rb:51:in `dispatch'
actionpack (6.0.1) lib/action_dispatch/routing/route_set.rb:33:in `serve'
actionpack (6.0.1) lib/action_dispatch/journey/router.rb:49:in `block in serve'
actionpack (6.0.1) lib/action_dispatch/journey/router.rb:32:in `serve'
actionpack (6.0.1) lib/action_dispatch/routing/route_set.rb:837:in `call'
我想我错过了将字符串参数常量化为实际类常量的部分。怎么办?
请指导。谢谢
通过查看uninitialized constant User::teacher
似乎您在某处使用较低版本,确保您在数据库中也有类型。应该是User::Teacher
正如Paula Fidalgo所说,以确保您在用户模型架构中将类型列作为字符串
之后,您可以在用户模型中创建新条目,如下所示
Teacher.create(user_params)
User.create(type: 'Teacher')
两者都是一样的。