【发布时间】:2021-08-08 14:32:34
【问题描述】:
在我的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,添加到belongs_to :assignment,在user模型中 -
我知道它必须去某个地方!它实际上继续
beloings_to: user而不是game。谢谢!
标签: ruby-on-rails parameters model controller