【问题标题】:Rails not letting after_create execute without user_id param. Why?Rails 不允许在没有 user_id 参数的情况下执行 after_create。为什么?
【发布时间】: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


【解决方案1】:

需要在分配模型上添加:optional =&gt; true

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-21
    • 2016-03-07
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    相关资源
    最近更新 更多