У меня есть User
, Assignment
и Department
модели.
Моя модель Assignment
имеет 2 belongs_to
ассоциации с моделью User
как requestor
и assignee
.
Модель User
и Assignment
также в свою очередь belongs_to
отдел.
Я хочу запустить проверку на моем Assignment
, чтобы все assignment
, requestor
и assignee
принадлежали одному и тому же отделу.
Это мой код для моделей
# app/models/assignment.rb
class Assignment < ApplicationRecord
belongs_to :requestor, class_name: "User", foreign_key: "requested_by"
belongs_to :assignee, class_name: "User", foreign_key: "assigned_to"
belongs_to :department
end
# app/models/user.rb
class User < ApplicationRecord
has_many :user_departments, class_name: "UserDepartment"
has_many :departments, through: :user_departments
belongs_to :department
end
# app/models/department.rb
class Department < ApplicationRecord
has_many :user_departments, class_name: "UserDepartment"
has_many :users, through: :user_departments
has_many :assignments
has_many :users
end
Это код для моего теста
# spec/factories/assignment.rb
FactoryBot.define do
sequence(:title) { |n| "Title #{n}" }
sequence(:description) { |n| "Description #{n}" }
factory :assignment do
title
description
image { Rack::Test::UploadedFile.new(Rails.root.join('spec/support/Floyd.jpeg'), 'image/jpeg') }
release_date { DateTime.now >> 1 }
department { create(:department) }
requestor create(:user, :bm, department: "I want to use the same department as created in earlier line here")
assignee create(:user, :mu, department: "I want to use the same department as created in earlier line here")
end
end
Где я должен определить отдел, чтобы я мог использовать один и тот же отдел во всех трех ассоциациях.