[RUBY] Existence check of has_many and belongs_to-optional: What is true?

Motivation

I think that it is necessary to check the existence of related destinations on the belongs_to side in many cases, but I did not encounter many related destinations on the has_many side, so I checked it.

Thing you want to do

Association of user model and team model. However, with the following restrictions.

--User must have at least one team. (Must belong to one or more teams) --On the contrary, there should be no team that is not related to user.

↓ This is the association. スクリーンショット 2020-09-04 19.28.21.png

environment

Rails 6.0.3 Ruby 2.7.1 mysql2 0.5.3

post model association

class Team < ApplicationRecord
    belongs_to :user
end

This is all you need for the post model. When you write belongs_to, ʻoptional: false` is applied by default. This imposes the constraint "post must always be associated with user".

On the contrary, if you want to create a "post that is not tied to user",

class Team < ApplicationRecord
    belongs_to :user, optional: true
end

It's OK if you write it like this. ʻOptional: true` does not necessarily have to be associated with user.

user model association

class User < ApplicationRecord
    has_many :teams
    validates :teams, presence: true
end

If you want to check the existence of related destinations on the has_many side, you need to add validation. If you do the above, you will be constrained that you must have at least one team.

Finally

I hope it helps someone.

Recommended Posts

Existence check of has_many and belongs_to-optional: What is true?
[Ruby] What is true?
What is Microservices? And Microservices Frameworks
[Ruby comprehension check] Can you explain what is happening? && and and
'% 02d' What is the percentage of% 2?
What kind of StringUtil is good
What is it? ~ 3 types of "no" ~
What kind of method is define_method?
What is testing? ・ About the importance of testing
What is Java and Development Environment (MAC)
What is the data structure of ActionText?
What is RSA signature verification and why?
What is JSP? ~ Let's know the basics of JSP !! ~
Check the version of the JDK installed and the version of the JDK enabled
What is the difference between SimpleDateFormat and DateTimeFormatter? ??
What are the advantages of DI and Thymeleaf?