在每列保存模型时,保存进度值

时间:2014-01-22 16:13:29

标签: ruby-on-rails ruby

我有一个名为CommonApp的模型,以及一个函数,它根据用户填写的数量生成进度%。

您可以在此处查看进度功能 - >

 def progress
  total_questions = self.attribute_names.count + 2

  # +4 for name, cities,industries,positions, associated models
  # -4 for id,  created_at, updated_at, user_id these will always be filled anyways
  # +2 for video, associated model, but weighed more heavily

  total_completed = 0 

  self.attribute_names.each do |attr|
   total_completed += 1 unless self[attr].blank?
  end

  total_completed = total_completed - 3
  # +1 name ( on user table, not on here
  # -4 for id,  created_at, updated_at, user_id

  total_completed += 1 if self.cities.any?
  total_completed += 1 if self.positions.any?
  total_completed += 1 if self.industries.any?
  total_completed += 2 if self.user.video

  (100.0*total_completed/total_questions).round

 end

我希望稍后按进度排序,因此这对我来说意味着最好的方法是在CommonApp中有一个名为progress的列,并在进度发生变化时更新列的值。

我该怎么做?

更新 我正在考虑下面的内容,每次进度函数运行时都会更新,并且与进度列的值不同。但是,我收到了错误 -

undefined method `save!' for 93:Fixnum

这是更新后的进度功能

 def progress
  total_questions = self.attribute_names.count + 2

  # +4 for name, cities,industries,positions
  # -4 for id,  created_at, updated_at, user_id 
  # +2 for video 

  total_completed = 0 

  self.attribute_names.each do |attr|
   total_completed += 1 unless self[attr].blank?
  end

  total_completed = total_completed - 3
  # +1 name
  # -4 for id,  created_at, updated_at, user_id 

  total_completed += 1 if self.cities.any?
  total_completed += 1 if self.positions.any?
  total_completed += 1 if self.industries.any?
  total_completed += 2 if self.user.video

  value = (100.0*total_completed/total_questions).round 

  unless self.progress_level == value 
    self.progress_level = value
    self.save!
  end

  (100.0*total_completed/total_questions).round

 end

1 个答案:

答案 0 :(得分:1)

使用迁移向当前模型添加列。

每次运行progress时都会更新这些列。几乎就像你现在这样做的方式: - )

<强>更新

虽然我喜欢在回调或观察者中这样做的想法,但我认为你可以按照目前的方式来应对。回调和观察者可能导致误导。对于这个简单的例子,我将它放在方法中。