DanielsV
DanielsV

Reputation: 892

How to pass parameter when duplicating object in rails controller?

How can I provide .dup method with custom param so every time it is executed param is always True even when object who is being duplicated has this param at false?

Attribute I want to make true is called :original.

Here is my Modifications_controller create action:

def create
    @modification = Modification.new(change_params.merge(user: current_user))

    respond_to do |format|
      if @modification.save

        @modification.entity.boxes.each do |b| 
          @modification.boxes << b.dup #here I need to pass custom param
        end

        format.js {}
      else
        format.js {} 
      end
    end
  end

Upvotes: 2

Views: 1367

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176412

#dup doesn't know anything specific about your model logic. If you want to set some attributes to true, simply clone the object and then change the values.

box = b.dup
box.value = true
@modification.boxes << box

You can also consider to extract the feature in a custom method in the model, so that it's easier to write a test for it.

def duplicate
  self.dup.tap do |i|
    i.value = true
  end
end

@modification.boxes << b.duplicate

Upvotes: 2

Related Questions