Search code examples
ruby-on-railsrubyvalidationmodel

Add Validation for Model creation


I have a Ruby on Rails project with 3 models: User, Group and Task. The idea is that users can be in different groups and groups can have different users, so member is a table in between connecting them.

The problem is that when doing the seeding:

puts "Creating Users"
admin_one = User.create!(email: "[email protected]", password: "1234567")
admin_two = User.create!(email: "[email protected]", password: "1234567")

puts "Creating Groups"
group_one = Group.create!(name: "Test Group One", description: "blablabla", admin: admin_one)
group_two = Group.create!(name: "Test Group Two", description: "blablabla", admin: admin_two)

puts "Creating Tasks"
task_one = Task.create!(name: "Task 1", user: user_one, group: group_one, assignee: admin_one)
task_two = Task.create!(name: "Task 2", user: admin_one, group: group_one, assignee: admin_one)
# Test if we can create tasks for users not part of the group
task_two = Task.create!(name: "Task 3", user: admin_one, group: group_one, assignee: admin_two)

I realized that even if admin_one is part of group_one, I can still create a Task with the assignee being admin_two (who is not related to that group at all).

Is there a way to set it so that the task assignee's group needs to be one that the user is in? Is a callback the only option or there are other ways to implement the logic?

Thanks!


Solution

  • You can use a custom validation for this:

    # in task model
    validate :assignee_in_correct_group
    
    def assignee_in_correct_group
      errors.add(:group_id, 'is not the same as assignee group id') unless assignee.groups.exist?(id: group.id)
    end