From the course: Ruby on Rails 6 Essential Training: Models and Associations

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Validate presence with belongs_to

Validate presence with belongs_to - Ruby on Rails Tutorial

From the course: Ruby on Rails 6 Essential Training: Models and Associations

Start my 1-month free trial

Validate presence with belongs_to

- [Instructor] In this movie, we're going to talk about that belongs_to relationship that we define on a model, so that we can understand about a validation requirement that it has. When you define belongs_to inside a model, the other object that that belongs_to is not optional. If it belongs to it, then that other object has to be assigned. So if we have a course that belongs to a teacher, the course has to have the teacher assigned. And Rails won't let us save the course to the database without that relationship being established. And it does that by adding a validation for the object's presence. We learned about validations in a previous chapter, that's all it's doing, it's behind the scenes, it's not just telling Rails how to work with the relationship and what foreign key to use, it actually adds a validation for the objects presence as well. This can often trip up beginners because it's happening in the…

Contents