Mathieu
Mathieu

Reputation: 4787

Ruby - Re-assign values to attributes

I have a belong_to/has_many relation between Deal and Step :

class Deal < ActiveRecord::Base

 has_many   :steps,          dependent:  :destroy do   
    def length
      reject(&:marked_for_destruction?).length
    end
  end 

accepts_nested_attributes_for :steps, allow_destroy: true

end

Step belongs to Deal and has an attribute called step_rank.

I would like to find a method to take all Steps and change the values of their step_ranks so that:

Let me give you an example if we have the following Steps fora given Deal (id:5 for example) initially:

Deal(id=5).step(id:1).step_rank = 15
Deal(id=5).step(id:4).step_rank = 4
Deal(id=5).step(id:7).step_rank = 9
Deal(id=5).step(id:37).step_rank = 30

then I need to find a way to transform those attribute's values into:

Deal(id=5).step(id:1).step_rank = 2
Deal(id=5).step(id:4).step_rank = 0
Deal(id=5).step(id:7).step_rank = 1
Deal(id=5).step(id:37).step_rank = 3

As you see the final values make a up a series of values starting at 0 and incrementing one by one while keeping the initial order.

I found a way to re-order them but not really to change each of their values. How to do it?

model/deal.rb

implement_increment( self.steps.reject(&:marked_for_destruction?).map{|u| u.step_rank} )

def implement_increment(array)
  sorted = array.sort
  lastNum = sorted[0]
  sorted[1, sorted.count].each do |n|
    lastNum = n
  end
  true
end 

Upvotes: 0

Views: 46

Answers (1)

user3309314
user3309314

Reputation: 2543

Try something like this:

Deal.find(5).steps.order(:step_rank).each_with_index do |step, index|
  step.update_attributes step_rank: index
end

Upvotes: 1

Related Questions