Search code examples
ruby-on-railsmodeloption-typebelongs-to

How do I make my belongs_to field optional?


I’m using Rails 5.0.0. I have this model

class Scenario < ApplicationRecord
  belongs_to :grading_rubric
  has_many :confidential_memo
end

but when I invoke my create method for the model, it fails

  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

The error I get is

full messages: ["Grading rubric must exist"]

How do I indicate that the belongs_to argument should be optional (that is, allowed to be null)?


Solution

  • It used to be that you could just leave the value as nil and Rails was perfectly happy. However this was changed in Rails 5.

    If you want the belongs_to to be optional, you simply have to pass optional: true:

    belongs_to :grading_rubric, optional: true
    

    You can find more info about it here