gpt4 book ai didi

ruby-on-rails - rails : Copying attributes from an object to another using the "attributes" method

转载 作者:数据小太阳 更新时间:2023-10-29 06:35:21 25 4
gpt4 key购买 nike

让模型 Quote 具有属性 [price, description]

让模型Invoice有属性[price, description, priority]

invoice 模型 Invoice 中的对象具有属性 {price: 10, description: 'lamp', priority: 10}

invoice = {price: 10, description: 'lamp', priority: 10}

假设我想将 invoice 属性复制到新的 quote

quote = Quote.new(invoice.attributes)

这会引发一个错误,即 priority 在模型 Quote 中不存在。

如何将 invoice 属性复制到新的 quote 但仅限 quote 可以接受的属性?

最佳答案

您可以 select只有 Quote 具有的属性:

Quote.new(invoice.attributes.select{ |key, _| Quote.attribute_names.include? key })

As noted by @aceofspades (但不是动态解决方案),您可以使用 ActiveSupport 的 slice还有:

Quote.new(invoice.attributes.slice(*Quote.attribute_names))

关于ruby-on-rails - rails : Copying attributes from an object to another using the "attributes" method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9590448/

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