Home > Enterprise >  Trouble with validation check for has_many :through association; how to create?
Trouble with validation check for has_many :through association; how to create?

Time:01-22

Rails newbie here. I am having trouble with ensuring the presence of at least one "has_many :through" relationship in my users model.

I have:

class User < ApplicationRecord
  has_many :company_users, dependent: :destroy
  has_many :companies, through: :company_users

  #validates :company_users, presence: true
end

class Company < ApplicationRecord
  has_many :company_users, dependent: :destroy
  has_many :users, through: :company_users   
end

class CompanyUser < ApplicationRecord
  belongs_to :user
  belongs_to :company
end

I got the commented validates line from the excellent answers at:

However when I implement this line, then doing the following in rails console:

c = Company.create
c.users.create!(email: "[email protected]")

gives

`raise_validation_error': Validation failed: Company users can't be blank (ActiveRecord::RecordInvalid)

From my newbie perspective, it seems like the HMT entry isn't created until after the user is created, which creates a validation error preventing the user in the first place! It's probably a very simple error, but how do I get the above behaviour to work with that validation in place?

I have tried setting inverse_of in a couple place, without any success.

And before it's mentioned, I'm purposefully using HMT instead of HABTM because I have additional attributes on the company_users model that will be set.

CodePudding user response:

One option would be to change the validation to

validates :companies, presence: true

and then create the user with

User.create(companies: [Company.create])

Edit:

Adding inverse_of to the CompanyUser model should also work. The validation would be left as validate :company_users, presence: true:

class CompanyUser
  belongs_to :user, inverse_of: :company_users
  belongs_to :company
end
  • Related