首页 > 解决方案 > Rails 不允许在没有 user_id 参数的情况下执行 after_create。为什么?

问题描述

在我的Game模型中,我有

class Game < ApplicationRecord
    has_many :assignments
    has_many :users, through: :assignments

    accepts_nested_attributes_for :assignments

    after_create :create_assignments

    def create_assignments
        3.times { Assignment.create!(game_id: id, user_id: 1) }
    end
end

这可行,但我需要在user_id创建时将其设为空白(稍后将对其进行编辑)。除非有一个值,否则它不会创建分配user_id

我试过把它留空并省略它,但这不起作用。我想我需要放在optional: true某个地方,但我对这个很困惑。

标签: ruby-on-railsparametersmodelcontroller

解决方案


需要添加:optional => true分配模型

class Assignment < ApplicationRecord
    belongs_to :game
    belongs_to :user, :optional => true
end

推荐阅读