Ruby on rails 使用复杂的计算功能更新rails数据库整个列
我有一张桌子。(normalusers)=>id、父id、高度。我在后面添加了高度栏。现在我想给它增值。我有什么办法可以做到这一点吗?我尝试过迁移,但没有更新高度。我认为函数在迁移中不起作用。移植后,所有行的高度值与之前相同Ruby on rails 使用复杂的计算功能更新rails数据库整个列,ruby-on-rails,Ruby On Rails,我有一张桌子。(normalusers)=>id、父id、高度。我在后面添加了高度栏。现在我想给它增值。我有什么办法可以做到这一点吗?我尝试过迁移,但没有更新高度。我认为函数在迁移中不起作用。移植后,所有行的高度值与之前相同 class Latest < ActiveRecord::Migration[6.0] def change i = 1 loop do i += 1 puts i record=N
class Latest < ActiveRecord::Migration[6.0]
def change
i = 1
loop do
i += 1
puts i
record=Normaluser.find(i)
record.height=get_height(record)
record.save!
if i == 39
break # this will cause execution to exit the loop
end
end
end
def get_height(record)
maxHeight=0
Normaluser.where(pid: record.id).each do |f|
tempHeight=get_height(f)
if tempHeight > maxHeight
maxHeight=tempHeight
end
end
return maxHeight
end
end
class-LatestmaxHeight
maxHeight=tempHeight
结束
结束
返回最大高度
结束
结束
运行一次性脚本来更新表的现有列的最佳方法是编写一个rake任务
在lib/tasks/
目录中,在该文件中创建一个名为update\u height.rake
namespace :update_latest_records do
desc 'Update height column of existing Latest'
task height: :environment do
# your update logic goes here
end
end
然后在ProjectHome中,运行rake命令
RAILS_ENV=development rake update_latest_records:height
在每个环境中传递正确的RAILS\u ENV
值,例如,要更新生产服务器中的记录,它应该是RAILS\u ENV=production
希望有帮助 请说明什么不起作用?你面临着什么错误吗?@Gautam这可以理解吗?是的,写函数没有错。我认为您应该进行调试,以查看从
get\u height
函数接收到的值是否正确。@Gautam在哪里可以看到put语句的输出?它在终端中不可见。运行迁移时,您应该能够看到put
语句的输出。