在我的模型中,我有多个has_one关联,如
has_one :t1_for_self_order, -> { t1_for_self_order }, as: :source, dependent: :destroy, inverse_of: :source,
class_name: 'Spree::PriceMapping'
has_one :shipping_charges_for_t1, -> { shipping_charges_for_t1 }, as: :source, dependent: :destroy, inverse_of: :source,
class_name: 'Spree::PriceMapping'
has_one :t2_for_self_order, -> { t2_for_self_order }, as: :source, dependent: :destroy, inverse_of: :source,
class_name: 'Spree::PriceMapping'
has_one :shipping_charges_for_t2, -> { shipping_charges_for_t2 }, as: :source, dependent: :destroy, inverse_of: :source,
class_name: 'Spree::PriceMapping'
has_one :minimum_value_for_gifting, -> { minimum_value_for_gifting }, as: :source, dependent: :destroy, inverse_of: :source,
class_name: 'Spree::PriceMapping'
has_one :international_fulfillment_fees, -> { international_fulfillment_fees }, as: :source, dependent: :destroy, inverse_of: :source,
class_name: 'Spree::PriceMapping'
您注意到,在所有关联中,只有具有相同作用域名称的关联名称不同,但其余内容相同。
所以我想写一个函数,去掉所有这些重复。我认为Meta编程是可能的,但我不确定如何进行
此外,我还有一个可以使用的嵌套属性数组。
THRESHOLD_INTENT = ["t1_for_self_order", "shipping_charges_for_t1", "t2_for_self_order", "shipping_charges_for_t2",
"minimum_value_for_gifting", "international_fulfillment_fees", "menu_customization_fee",
"total_menu_customization_fee_cap", "video_message_fee", "total_video_message_fee_cap",
"swag_price", "box_types_with_price", "customization_box_types_with_price", "custom_note_fee",
"non_us_fees"]
我喜欢用这种方式
THRESHOLD_INTENT.each do |t_intent|
has_one t_intent.to_sym, as: :source, dependent: :destroy, inverse_of: :source, class_name: 'Spree::PriceMapping'
end
但是我怎么能像一样缩小范围呢
>{t1_for_self_order}
您可以迭代关联名称列表,并使用每个项上的所有参数调用has_one
。需要CCD_ 2来调用关联作用域作为方法。
ASSOCIATIONS = [:t1_for_self_order, :shipping_charges_for_t1, :t2_for_self_order, :shipping_charges_for_t2, :minimum_value_for_gifting, :international_fulfillment_fees]
ASSOCIATIONS.each do |association|
has_one association, -> { send(association) }, as: :source, dependent: :destroy, inverse_of: :source, class_name: 'Spree::PriceMapping'
end
尝试提取常见属性,比如
relationship_attributes = { as: :source, dependent: :destroy, inverse_of: :source, class_name: 'Spree::PriceMapping' }
has_one :t1_for_self_order, -> { t1_for_self_order }, relationship_attributes
has_one :shipping_charges_for_t1, -> { shipping_charges_for_t1 }, relationship_attributes
has_one :t2_for_self_order, -> { t2_for_self_order }, relationship_attributes
has_one :shipping_charges_for_t2, -> { shipping_charges_for_t2 }, relationship_attributes
has_one :minimum_value_for_gifting, -> { minimum_value_for_gifting }, relationship_attributes
has_one :international_fulfillment_fees, -> { international_fulfillment_fees }, relationship_attributes
我不会使用元编程,它会使阅读变得困难