Rails: Copying attributes from an object to another using the “attributes” method

前端 未结 4 1758
野趣味
野趣味 2020-12-14 18:26

Let model Quote have attributes [price, description]

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

4条回答
  •  一向
    一向 (楼主)
    2020-12-14 19:10

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

提交回复
热议问题