【问题标题】:Ruby - Re-assign values to attributesRuby - 将值重新分配给属性
【发布时间】:2018-01-16 23:18:46
【问题描述】:

我在 Deal 和 Step 之间有一个belong_to/has_many 关系:

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 属于 Deal 并且有一个名为 step_rank 的属性。

我想找到一种方法来采取所有步骤并更改其 step_ranks 的值,以便:

  • 最低的初始 step_rank 值为 0

  • 其他人,在初始 step_rank 方面保持相同的“顺序”,只需在最后组成一个增量为 +1 的系列

如果我们最初对给定的交易(例如 id:5)有以下步骤,让我举个例子:

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

那么我需要找到一种方法将这些属性的值转换为:

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

如您所见,最终值构成了一系列值,从 0 开始并在保持初始顺序的同时逐个递增。

我找到了一种重新排序它们的方法但并没有真正改变它们的每个值。怎么做?

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 

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    试试这样的:

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

    【讨论】:

    • id 5 只是一个示例,我将尝试使用 self.steps.order(:step_rank).each_with_index do |step, index| step.update_attributes step_rank:索引结束
    • 我收到错误:#<0x00000004edf428>
    • &:marked_for_destruction
    猜你喜欢
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多