ruby 为模型创建添加验证

xzv2uavs  于 2023-02-08  发布在  Ruby
关注(0)|答案(1)|浏览(143)

我有一个Ruby on Rails项目,包含3个模型:用户、组和任务。其思想是用户可以在不同的组中,组可以有不同的用户,因此成员是连接它们之间的表。
问题是在做播种时:

puts "Creating Users"
admin_one = User.create!(email: "jose@test.io", password: "1234567")
admin_two = User.create!(email: "joe@test.io", 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)

我意识到,即使admin_onegroup_one的一部分,我仍然可以创建一个Task,其受让人是admin_two(与该组完全无关)。
是否有办法设置它,以便任务受让人的组必须是用户所在的组?callback是唯一的选项还是有其他方法实现该逻辑?
谢谢!

nwlqm0z1

nwlqm0z11#

您可以为此使用自定义验证:

# 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

相关问题