ruby-on-rails - 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
某个地方,但我对这个很困惑。
解决方案
需要添加:optional => true
分配模型
class Assignment < ApplicationRecord
belongs_to :game
belongs_to :user, :optional => true
end
推荐阅读
- java - 在 Jenkins 上配置 GitHub
- javascript - 如何从 for 循环中获取每个值
- aspnetboilerplate - 在 Dapper ASP.Net 核心样板中删除不起作用
- qlikview - 如何打开 qlikview 管理控制台?
- node.js - 如何通过@google/maps 获取有效地址?
- docker - 构建 Dockerfile 得到错误,因为 pynacl 的构建轮失败
- database - ORA-28040: 将数据库从 11g 升级到 12c 后
- powerbi - Power BI:如何选择 Power BI 中日期较大的所有列
- asp.net - 无法索引到 System.Xml.XPathNodeList 类型的对象
- android - 位置数据源不加载所有数据