4 model ruby-on-rails optional belongs-to
我正在使用 Rails 5.0.0。我有这个模型
class Scenario < ApplicationRecord
belongs_to :grading_rubric
has_many :confidential_memo
end
Run Code Online (Sandbox Code Playgroud)
但是当我为模型调用我的 create 方法时,它失败了
def create
@scenario = Scenario.new(scenario_params)
respond_to do |format|
if @scenario.save
puts "saved successfully."
format.html { redirect_to confidential_memo_path(@scenario), notice: 'Saved successfully.' }
else
puts "full messages: #{@scenario.errors.full_messages}"
format.html { render action: "show" }
end
end
end
Run Code Online (Sandbox Code Playgroud)
我得到的错误是
full messages: ["Grading rubric must exist"]
Run Code Online (Sandbox Code Playgroud)
我如何指示belongs_to 参数应该是可选的(即允许为空)?
过去,您可以将值保留为 asnil并且 Rails 非常满意。然而,这在 Rails 5 中发生了变化。
如果你想belongs_to是可选的,你只需要通过optional: true:
belongs_to :grading_rubric, optional: true
Run Code Online (Sandbox Code Playgroud)
您可以在此处找到有关它的更多信息
| 归档时间: |
|
| 查看次数: |
3506 次 |
| 最近记录: |