扶手:使用&QUOT复制从一个对象的属性到另一个;属性"方法 [英] Rails: Copying attributes from an object to another using the "attributes" method

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

问题描述

让模型引用有属性 [价格,说明】

让模型发票有属性 [价格,描述,优先级]

发票从模型中的对象发票带属性的 {价:10,说明:'灯',优先级:10}

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

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

比方说,我想复制发票属性到一个新的报价

quote = Quote.new(invoice.attributes)

这引发了错误的优先级不existe模型引用

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

如何复制发票属性到一个新的报价但只有属性,一个报价能接受吗?

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

推荐答案

可以的 选择 引用的属性:

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

所指出的@aceofspades (但不与动态解决方案),你可以请使用ActiveSupport的的 还有:

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))

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

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