gpt4 book ai didi

ruby-on-rails - 如何在 factory_girl 中创建一个对象来验证它至少有一个关联对象?

转载 作者:太空宇宙 更新时间:2023-11-03 16:26:22 24 4
gpt4 key购买 nike

有如下代码:

  let!(:beauty_salon_service) { create(:beauty_salon_service) }
let!(:beauty_salon_employee) { build(:beauty_salon_employee,
business: beauty_salon_service.beauty_salon_category.business) }
before do
beauty_salon_employee.beauty_salon_employee_services.build(beauty_salon_service: beauty_salon_service)
beauty_salon_employee.save!
end

两个条件:

  1. beauty_salon_service 和 beauty_salon_employee 必须指向相同的业务(你可以看到);
  2. beauty_salon_employee 一定没有 空白 has_many 通过协会 beauty_salon_employee_services (验证存在);

我的 FactoryGirl 代码不起作用 - “验证失败:美容院员工服务不能为空”。我该如何解决?提前致谢。

最佳答案

let! 发生在 before 之前,因此创建员工时没有服务(您可能知道这一点)。要解决眼前的问题,您需要在创建员工时提供服务。

当你在 factory_girl 中(或在 ActiveRecord 中,就此而言)创建一个对象时,你可以像这样初始化一个多对多关系:

let!(:beauty_salon_employee) do
build :beauty_salon_employee,
business: beauty_salon_service.beauty_salon_category.business,
beauty_salon_employee_services: [beauty_salon_service]
end

尽管您真正想要做的可能是在 BeautySalonFactory 中创建 BeautySalonService。 The factory_girl documentation for associations给出一个如何在回调中填充一对多关联的示例:

FactoryGirl.define do

# post factory with a `belongs_to` association for the user
factory :post do
title "Through the Looking Glass"
user
end

# user factory without associated posts
factory :user do
name "John Doe"

# user_with_posts will create post data after the user has been created
factory :user_with_posts do
# posts_count is declared as a transient attribute and available in
# attributes on the factory, as well as the callback via the evaluator
ignore do
posts_count 5
end

# the after(:create) yields two values; the user instance itself and the
# evaluator, which stores all values from the factory, including transient
# attributes; `create_list`'s second argument is the number of records
# to create and we make sure the user is associated properly to the post
after(:create) do |user, evaluator|
create_list(:post, evaluator.posts_count, user: user)
end
end
end
end

在您的情况下,您需要使用 before_create 而不是 after_create 来满足您的验证。

关于ruby-on-rails - 如何在 factory_girl 中创建一个对象来验证它至少有一个关联对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24081294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com