Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

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

Let model Quote have attributes [price, description]

Let model Invoice have attributes [price, description, priority]

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

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

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

quote = Quote.new(invoice.attributes)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can select only the attributes that Quote has:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...