gpt4 book ai didi

ruby-on-rails - 如何通过 factorygirl 中的特征将属性传递给关联?

转载 作者:数据小太阳 更新时间:2023-10-29 08:07:11 26 4
gpt4 key购买 nike

考虑以下模型设置

class Template < ActiveRecord::Base
belongs_to :detail, polymorphic: true, dependent: :destroy
accepts_nested_attributes_for :detail
end

class EbayTitleTemplate < ActiveRecord::Base
has_one :template, as: :detail
end

这是一个正在运作的工厂

FactoryGirl.define do
factory :template do
merchant
channel

trait :ebay_title do
association :detail, factory: :template_ebay_title
end

factory :ebay_title_template, traits: [:ebay_title]
end

factory :template_ebay_title, class: EbayTitleTemplate do
name "eBay Title Template"
title "Super Cool Hat"
sub_title "Keeps the sun away"
description "The best hat available!"
end
end

以下对我有用

create(:ebay_title_template)  # creates both records, creating a new Merchant and Channel for me
create(:ebay_title_template, merchant: Merchant.first, channel: Channel.first) # creates both records with explicit channel and merchant

现在我还想做的是传入自定义属性以覆盖默认值。像这样:

create(:ebay_title_template, title: "Overwrite the title", sub_title: "Overwrite the subtitle")

最终发生的是我收到错误 ArgumentError: Trait not registered: title

FactoryGirl 不知何故认为我传递了一个特征,或者模板工厂没有将 title 识别为一个属性。

我试过使用 transient 允许自定义参数通过模板并使用 :template_ebay_title 工厂中的回调将属性映射到模型列,如下所示:

transient do
custom_args nil
end

after(:create) do |record, evaluator|
evaluator.custom_args.each do |key, value|
record.key = value
end
end

然后我这样创建:

create(:ebay_title_template, custom_args: {title: "Overwrite", sub_title: "Overwrite"})

这会导致错误 NoMethodError: undefined methodcustom_args' for #`

所以要么有办法做到这一点,但我做错了,要么我需要一种全新的方法。请记住,将有许多关联需要定义为特征(或其他),因此我不可能指定要传递的特定瞬变。

我怎样才能实现我的目标,即创建一个创建父对象和多态关联的工厂,允许我为多态关联传递任意属性,并返回父对象?

最佳答案

如果你想传递单个哈希值中的值,你需要像这样传递它们:

create(:ebay_title_template, custom_args: {title: "Overwrite the title", sub_title: "Overwrite the subtitle"})

否则您可以创建新的 transient 值,并按照您现在传递它们的方式传递它们:

transient do     # use ignore with FactoryGirl/FactoryBot < v4.7
title nil
sub_title nil
end

当像上面那样添加更多属性时,您可以迭代评估器的覆盖实例变量:

evaluator.instance_variable_get(:@overrides).each do |key, value|
puts key, value
end

希望对您有所帮助!

关于ruby-on-rails - 如何通过 factorygirl 中的特征将属性传递给关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40270912/

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