Ruby on rails 在模型的每个保存列上,保存进度值
我有一个名为CommonApp的模型,上面有一个函数,根据用户填写的内容生成进度% 您可以在此处查看进度函数--> 我想稍后按进度排序,因此这对我来说意味着最好的方法是在CommonApp中有一个名为progress的列,并在进度发生变化时更新该列的值 我该怎么做 更新 我在想下面的内容,它将在每次运行progress函数时更新,并且与progress列的值不同。但是,我得到了一个错误-- 这是更新的进度函数Ruby on rails 在模型的每个保存列上,保存进度值,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一个名为CommonApp的模型,上面有一个函数,根据用户填写的内容生成进度% 您可以在此处查看进度函数--> 我想稍后按进度排序,因此这对我来说意味着最好的方法是在CommonApp中有一个名为progress的列,并在进度发生变化时更新该列的值 我该怎么做 更新 我在想下面的内容,它将在每次运行progress函数时更新,并且与progress列的值不同。但是,我得到了一个错误-- 这是更新的进度函数 def progress total_questions = self.attr
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
使用迁移将列添加到当前模型 无论何时运行
progress
,都会更新该列。就像你现在做的那样:-)
更新
虽然我喜欢在回调或观察者中执行此操作,但我认为您可以按照当前的方式进行操作。回调和观察者可能会导致误导。对于这个简单的例子,我将它保留在方法中。您可以使用
before_action
过滤器来检查参数并相应地附加/更改进度参数(?)。您可以使用Rails的observer模块来观察增加/减少CommonApp进度的对象,并更新数据库中的相关进度值。@MrYoshiji观察员在Rails 4.0中正式弃用。对吗?嘿,伙计们,添加了一个快速更新,其中包含一个在函数内部工作的想法,这样我就不需要在函数本身之外跟踪太多内容了。但是,我确实犯了一个错误。你怎么看?自救!不是自我。进步\等级。保存!
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