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

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

Let model Quote have attributes [price, description]

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

相关标签:
4条回答
  • 2020-12-14 18:55

    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))
    
    0 讨论(0)
  • 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))
    
    0 讨论(0)
  • 2020-12-14 19:11
    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.
    
    0 讨论(0)
  • 2020-12-14 19:16

    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)
    
    0 讨论(0)
提交回复
热议问题