Let model Quote
have attributes [price, description]
Let model Invoice
have attributes [price, description, priority]
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))
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))
sample_plan = Plan.last # it contains object we want to convert
new_plan = Addon.new(sample_plan.attributes.except(:id)) # remove that particular column which is not common else you can get attribute errors.
new_plan # you can get the copy object with data in new one.
The straightforward way is something like this:
source = invoice.attributes
target = (source.keys & Quote.attribute_names).inject({}) {|target, key| target[key] = source[key]; target }
quote = Quote.new(target)