Rails中after_create回调无user_id参数不执行是什么原因?
解决方案
- 第一步:修改Assignment模型的关联配置
Rails 5及以上版本中,belongs_to关联默认会开启必填校验,你需要在Assignment模型中对user关联添加optional: true参数:
class Assignment < ApplicationRecord belongs_to :game belongs_to :user, optional: true # 新增optional: true配置 # 其他原有代码 end
- 第二步:(可选)移除数据库层的非空约束
如果你创建assignments表时给user_id字段设置了null: false的非空约束,还需要生成迁移文件解除该约束:- 执行命令生成迁移:
rails g migration RemoveNullConstraintFromAssignmentsUserId - 编辑生成的迁移文件内容:
class RemoveNullConstraintFromAssignmentsUserId < ActiveRecord::Migration[你对应的Rails版本号] def change change_column_null :assignments, :user_id, true end end- 执行迁移生效:
rails db:migrate
- 执行命令生成迁移:
- 第三步:修改Game模型的创建逻辑
调整create_assignments方法,去掉user_id参数的传递:
def create_assignments 3.times { Assignment.create!(game_id: id) } end
额外注意:如果你的Assignment模型中单独写了
validates :user_id, presence: true的存在性校验,也需要将该行删除。
内容的提问来源于stack exchange,提问作者wayoh22
相关产品推荐
相关产品推荐

