英文:
Add Validation for Model creation
问题
我有一个Ruby on Rails项目,包括3个模型:User(用户)、Group(群组)和Task(任务)。
思路是用户可以属于不同的群组,群组可以有不同的用户,因此成员是一个连接它们的中间表。
问题在于在进行种子数据填充时:
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)
# 测试是否可以为不属于该群组的用户创建任务
task_two = Task.create!(name: "Task 3", user: admin_one, group: group_one, assignee: admin_two)
我发现即使admin_one
属于group_one
,我仍然可以创建一个将assignee设置为admin_two
(与该群组无关的用户)的Task
。
有没有一种方法可以设置任务的assignee必须是用户所在的群组之一?是回调函数是唯一的选项,还是有其他实现这一逻辑的方式?
谢谢!
英文:
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: "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)
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!
答案1
得分: 3
你可以为此使用自定义验证:
# 在任务模型中
validate :assignee_in_correct_group
def assignee_in_correct_group
errors.add(:group_id, '与被分配者的组ID不同') unless assignee.groups.exists?(id: group.id)
end
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论