Factory Bot 与命名空间模型故障的关联
Factory Bot associations with namespaced model glitching
当尝试构建命名空间关联时,Factorybot 不注册命名空间,而是使用它自己的命名空间,尽管定义它就像文档一样(SO 上的每个线程都说)。
型号Admin::TicketCategory
class Admin::TicketCategory < ApplicationRecord
has_many :tickets
end
及其工厂:
FactoryBot.define do
factory :ticket_category, class: Admin::TicketCategory do |f|
f.text { Faker::Commerce.product_name }
end
end
Ticket
型号:
class Ticket < ApplicationRecord
belongs_to :user
belongs_to :service_rep, class_name: 'User', foreign_key: :user_id
belongs_to :ticket_category
belongs_to :ticket_status
belongs_to :ticket_urgency
has_many :ticket_comments
end
及其工厂:
FactoryBot.define do
factory :ticket do |f|
f.user
f.ticket_category
f.subject { Faker::Lorem.sentence }
f.body { Faker::Lorem.paragraph }
f.ticket_urgency { admin_ticket_urgency }
f.ticket_status { admin_ticket_status }
f.service_rep { user }
end
end
当我尝试验证 Ticket
模型时,出现此错误:
1) Ticket has a valid factory
Failure/Error: expect(FactoryBot.create(:ticket)).to be_valid
NameError:
uninitialized constant Ticket::TicketCategory
如有任何帮助,我们将不胜感激!
以下是 rails 命名空间模型的工作原理:
它将尝试找出当前命名空间中的关联模型。
让我们从您定义的关联开始:
在 Admin::TicketCategory
中它应该有 has_many: tickets, class_name: "Ticket"
(假设你在 Ticket
模型中有 ticket_category_id
)。在你的 Ticket
模型中你应该有 belongs_to: ticket_category, class_name: "Admin::TicketCategory
.
这应该足以让它工作
当尝试构建命名空间关联时,Factorybot 不注册命名空间,而是使用它自己的命名空间,尽管定义它就像文档一样(SO 上的每个线程都说)。
型号Admin::TicketCategory
class Admin::TicketCategory < ApplicationRecord
has_many :tickets
end
及其工厂:
FactoryBot.define do
factory :ticket_category, class: Admin::TicketCategory do |f|
f.text { Faker::Commerce.product_name }
end
end
Ticket
型号:
class Ticket < ApplicationRecord
belongs_to :user
belongs_to :service_rep, class_name: 'User', foreign_key: :user_id
belongs_to :ticket_category
belongs_to :ticket_status
belongs_to :ticket_urgency
has_many :ticket_comments
end
及其工厂:
FactoryBot.define do
factory :ticket do |f|
f.user
f.ticket_category
f.subject { Faker::Lorem.sentence }
f.body { Faker::Lorem.paragraph }
f.ticket_urgency { admin_ticket_urgency }
f.ticket_status { admin_ticket_status }
f.service_rep { user }
end
end
当我尝试验证 Ticket
模型时,出现此错误:
1) Ticket has a valid factory
Failure/Error: expect(FactoryBot.create(:ticket)).to be_valid
NameError:
uninitialized constant Ticket::TicketCategory
如有任何帮助,我们将不胜感激!
以下是 rails 命名空间模型的工作原理: 它将尝试找出当前命名空间中的关联模型。
让我们从您定义的关联开始:
在 Admin::TicketCategory
中它应该有 has_many: tickets, class_name: "Ticket"
(假设你在 Ticket
模型中有 ticket_category_id
)。在你的 Ticket
模型中你应该有 belongs_to: ticket_category, class_name: "Admin::TicketCategory
.
这应该足以让它工作