Factory-bot-如何建立关联和嵌套属性 [英] Factory-bot - How to build association and nested attributes
本文介绍了Factory-bot-如何建立关联和嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是工厂的新手,我需要有关关联和嵌套属性的帮助....
I am new to Factories and I need help for the association and nested attributes....
- 如何设置创建产品的管理员用户?好
- 如何为产品设置类别?好吧
-
如何将图像附加到产品上?确定
- How do I set an admin user that creates a product? OK
- How do I set category to a product? Ok
How do I attach images to a product? OK
我如何设置产品的尺寸(巢状服装)
How do I set product's sizes (nested attibutes)
user.rb
has_many :products
product.rb
product.rb
belongs_to :user
belongs_to :category
has_many :sizes, inverse_of: :product, dependent: :destroy #nested_attributes
size.rb
belongs_to :product
category.rb
category.rb
has_many :products
factories/users.rb
factories/users.rb
FactoryBot.define do
factory :user do
first_name { Faker::Name.first_name}
last_name { Faker::Name.last_name }
admin { [false, true].sample }
sequence(:email) { |n| "#{n}#{Faker::Internet.email}" }
birth_date {"20/10/1997"}
password { 'password'}
end
end
factories/categories.rb
factories/categories.rb
FactoryBot.define do
factory :category do
title { Faker::Artist.name }
end
end
factories/sizes.rb
factories/sizes.rb
FactoryBot.define do
factory :size do
size_name {["S", "M", "L", "XL"].sample }
quantity { Faker::Number.number(2) }
end
end
factories/products.rb
factories/products.rb
FactoryBot.define do
factory :product do
title { Faker::Artist.name}
ref { Faker::Number.number(10)}
price { Faker::Number.number(2) }
color { Faker::Color.color_name }
brand { Faker::TvShows::BreakingBad }
description { Faker::Lorem.sentence(3) }
size
category
# how to set an admin ??
end
end
推荐答案
添加这样的关联
对于产品
FactoryBot.define do
factory :product do
user {User.first || association(:user)}
user {User.first || association(:user, admin: true)}
# your admin attribute (role: admin or admin: true) whatever you are using for admin
category {Category.first || association(:category)}
end
end
阅读 FactoryBot关联希望对您有所帮助.
Read FactoryBot association hope it will help.
这篇关于Factory-bot-如何建立关联和嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文