Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 200
Laura Avatar asked Mar 06 '12 19:03

Laura


2 Answers

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))
like image 199
Andrew Marshall Avatar answered Sep 29 '22 14:09

Andrew Marshall


How about the slice method from ActiveSupport?

quote = Quote.new(invoice.attributes.slice(:price, :description))

or even

quote = Quote.new(invoice.attributes.slice(*Quote.accessible_attributes))
like image 34
aceofspades Avatar answered Sep 29 '22 14:09

aceofspades