[Ruby] [Rails] What to do when data is not registered in DB

less than 1 minute read

Introduction

I want to save the form input contents in DB, but I was addicted, so output

Environment

Rails 5.0.7.2 ruby 2.5.1 mysql 14.14

problem

When I try to save the form input, it is saved in the parameter but not in the DB.

Workaround

Add! After the method to save and check the cause.

Then, validation failed:User must exist (error content may differ)

Cause

The cause is that the relevant foreign key is not entered and the validation is played when the association is set up.

Describe optional: true.

goal.rb


class Goal <ApplicationRecord

  validates :name, presence: true, uniqueness: true
  validates :time, presence: true, uniqueness: true
  validates :days, presence: true, uniqueness: true
  belongs_to :user, optional: true # edit here
end

optional: true is to allow nil foreign keys of belongs_to.

Now you can save it in DB. please refer!