【问题标题】:Factory-bot - How to build association and nested attributesFactory-bot - 如何建立关联和嵌套属性
【发布时间】:2019-02-11 09:52:13
【问题描述】:

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

  • 如何设置创建产品的管理员用户?好的
  • 如何为产品设置类别?好的
  • 如何将图像附加到产品上?好的

  • 如何设置产品尺寸(嵌套属性)

用户.rb

 has_many :products

产品.rb

belongs_to :user
belongs_to :category
has_many :sizes, inverse_of: :product, dependent: :destroy #nested_attributes 

大小.rb

belongs_to :product

类别.rb

has_many :products

工厂/用户.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

工厂/类别.rb

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

工厂/大小.rb

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

工厂/产品.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

【问题讨论】:

    标签: ruby-on-rails factory-bot


    【解决方案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 association希望对您有所帮助。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    相关资源
    最近更新 更多