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.
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.
Rails 6.0.3 Ruby 2.7.1 mysql2 0.5.3
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.
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.
I hope it helps someone.
Recommended Posts