工厂机器人 - 如何建立协会和嵌套属性(Factory-bot - How to build ass

2019-09-29 01:37发布

我是新来的工厂,我需要帮助的关联和嵌套属性....

  • 如何设置,创建一个产品一个管理员用户? 好
  • 如何设置类别的产品? 好
  • 如何重视图像的产品? 好

  • 如何设置产品的尺寸(嵌套attibutes)

user.rb

 has_many :products

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

has_many :products

工厂/ 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

工厂/ categories.rb

FactoryBot.define do
  factory :category do
    title { Faker::Artist.name }
  end
end

工厂/ sizes.rb

FactoryBot.define do 
    factory :size do 
        size_name {["S", "M", "L", "XL"].sample }
        quantity  { Faker::Number.number(2) }
    end
end

工厂/ 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

Answer 1:

加入这样的社团

有关产品

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协会希望这将有助于。



文章来源: Factory-bot - How to build association and nested attributes