gangothri
gangothri

Reputation: 168

Dilemma to choose the association for following usecase in rails model association

In a playstation app I have a User model, which already has has_many through association with roles and user_roles. Now our requirement asks us to create a team model, which has one captain and that captain is a user (one record of user model) and at the same time, a team has many users as players. I implemented the scenario with the following way

class User < ApplicationRecord
  has_many :user_roles
  has_many :roles, through: :user_roles, :dependent => :destroy
  belongs_to :team
end

class Team < ApplicationRecord
    has_one :captain, class_name: 'User' , foreign_key: 'captain_id'
     has_many  :users, dependent: :destroy
end

My problem is that I am not able to create a user without a team. When I am creating a new user it is asking team must exist. Our plan is to create a user and then we will assign each user as players and out of them, one will be a captain. So please guide me if my thought process is wrong about the use case and also suggest me the perfect association style for the use case.

Upvotes: 1

Views: 56

Answers (1)

Vasilisa
Vasilisa

Reputation: 4640

Starting from Rails 5, belongs_to association validates presence by default. You can change it with optional option:

class User < ApplicationRecord
  belongs_to :team, optional: true
end

Upvotes: 3

Related Questions