This time, we will learn what to do when you do not know the cause of rollback when saving with rails.
Currently creating a site where users can register notes.
What I want to do this time Send registration (note) from from, save it in DB (linked to user) and display it in view
Where I struggled It rolls back when I register.
@ note.save! I got the following error, so I searched
ActiveRecord::RecordInvalid: Validation failed: User must exist
In summary, it seems that the user model had no value and was played by validation
optional: Describe true
note.rb
class Note < ApplicationRecord
belongs_to :user,optional: true
validates :title, presence: true
validates :explanation, presence: true
end
optional: What is true?
Optional: What is true for Rails belongs_to? Allowing the foreign key nil of belongs_to
reference
The rollback has been resolved, but all the posted titles are displayed as 0.
Cause
This was because the title data type of the migration file was integer.
Change it to text type and do rails db: migration: reset
to solve it!
Recommended Posts