Search code examples
ruby-on-railsobjectmergeinstances

Ruby on Rails merge several objects into one


I have following problem:

I have a Class named Foo and some instances of this Class like this:

@foo1
@foo2
@foo3

Each of these instances has an attribute called :description with a text in it like this:

@foo1.description = "Lorem"
@foo2.description = "ipsum"
@foo3.description = "dolore"

Now I would like to merge/combine the three objects above so that I afterward have only one instance like this:

@foo1.description = "Lorem ipsum dolore"

Has anyone an idea how i could do this merging?

Thanks.

EDIT MORE CONTEXT:

I have a class named Risk and a lot of instances. The attributes of an instance of the Risk class are id, description, issue, references and target_ids as an instance of the Risk class can has_many targets.

In my Risk Index view where it displays all Risks I'd like to have an additional checkbox column where i can check all the risks I'd like to merge. Then there is a button called "Merge" and if the button is pressed all the Risks which are checked in the checkbox should be merged into the first one which is checked.


Solution

  • @foo1.description = "Lorem"
    @foo2.description = "ipsum"
    @foo3.description = "dolore"
    @foos = @foo1 + @foo2 + @foo3
    
    desc_array = []
    @foos.each do |foo|
      desc_array << foo.description
    end
    
    @foo1.description = desc_array.join
    @foo1.description.save()