Rails:使用“属性"将属性从一个对象复制到另一个对象方法 [英] Rails: Copying attributes from an object to another using the "attributes" method

查看:28
本文介绍了Rails:使用“属性"将属性从一个对象复制到另一个对象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

invoice 来自模型 Invoice 的对象具有 {price: 10, description: 'lamp', priority: 10}

Let invoice an object from Model Invoice with attributes {price: 10, description: 'lamp', priority: 10}

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

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

Let's say I want to copy invoice attributes to a new quote.

quote = Quote.new(invoice.attributes)

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

This raises an error that priority does not existe in model Quote.

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

How do I copy invoice attributes to a new quote but only the attributes that a quote can accept?

推荐答案

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

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

如@aceofspades 所述(但不是动态解决方案),您可以使用 ActiveSupport 的 slice 以及:

As noted by @aceofspades (but not with a dynamic solution), you can use ActiveSupport's slice as well:

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

这篇关于Rails:使用“属性"将属性从一个对象复制到另一个对象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆