Reputation: 2118
I am creating a new instance of a working application, and try to seed the User model. One custom validation fails at seeding , but works fine in normal operation:
The User model is linked to the Group model through a HABTM relation. A user must at least belong to the group Everyone, of which id is 0.
user.rb
class User < ApplicationRecord
# Validations
validate :member_of_Everyone_group
# Relations
has_many :groups_users
has_many :groups, through: :groups_users
private
def member_of_Everyone_group
errors.add(:base, :EveryoneMembershipMissing) unless self.group_ids.include? 0
end
end
group.rb
class Group < ApplicationRecord
# Relations
has_many :groups_users
has_many :users, through: :groups_users
end
groups_user.rb
class GroupsUser < ApplicationRecord
### Validations
validates :is_principal, uniqueness: { scope: [:group_id, :user_id] }
validates :group_id, uniqueness: { scope: :user_id }
belongs_to :users
belongs_to :groups
end
At seeding, the following error is raised:
rails aborted! NameError: uninitialized constant User::Groups
app/models/user.rb:174:in `member_of_Everyone_group'
group_ids.include? 0
works fine tooCan you help me to understand what's going wrong ?
Thanks a lot!
Upvotes: 0
Views: 102
Reputation: 725
A user has_many
groups, but in groups_user.rb
there is a uniqueness validation for group_id
in the scope of user. This seems to be a contradiction.
Upvotes: 0
Reputation: 151
belongs_to
should use the singular version of the model name, not the plural. In your GroupsUser
model, change those lines to:
belongs_to :user
belongs_to :group
Upvotes: 1