How can I validate two attributes in a rails model?

0

Good afternoon friends of stackoverflow.

I have the following model, which is a weak table from many to many, in which I want to validate two attributes that do not repeat themselves within the table, for example:

I have groups and activities what I want is that the group and the activity those two do not repeat themselves internally in whose database table.

Help me, I'm going to blow my head.

Here's the model:

Permission.rb

class Permission < ApplicationRecord
  belongs_to :activity
  belongs_to :group
end

Group.rb

class Group < ApplicationRecord
    has_many :memberships
    has_many :users, through: :memberships 
    has_many :permissions
    has_many :activities, through: :permissions
    has_many :users, through: :memberships
    validates :name, presence: true, uniqueness: true
end

Activity.rb

class Activity < ApplicationRecord
    has_many :permissions
    has_many :groups, through: :permissions
end
    
asked by Tysaic 26.01.2018 в 20:01
source

1 answer

1

Put the following validation in Permission.rb

validates :activity_id, uniqueness: { scope: : group_id }

or in the following way should also work

validates :activity, uniqueness: { scope: : group }

With this you will not have repeated in the table permissions.

    
answered by 27.01.2018 / 00:10
source