如何在Rails 4上向我的表添加求和列

时间:2022-04-25 20:24:47

I have an already existing table "registers" with columns; :full_name, :amount_paid, :user_id, :course_id. I also have the course table with columns: :title, :price.

我有一个已经存在的表“寄存器”列; :full_name,:amount_paid,:user_id,:course_id。我还有包含列的课程表:: title,:price。

I want to add a column to my registers table that calculate the balance from the register.course.price and the register.

我想在register表中添加一列来计算register.course.price和寄存器的余额。

so I tried

所以我试过了

rails g migration add_balance_to_registers balance:"register.course.price - register.amount_paid"

rails g migration add_balance_to_registers余额:“register.course.price - register.amount_paid”

but when I try

但是当我尝试

rake db:migrate

I get an error

我收到一个错误

1 个解决方案

#1


You can add the field to registers table, then populate it with appropriate values.

您可以将该字段添加到register表,然后使用适当的值填充它。

First you add field with new migration

首先,使用新迁移添加字段

rails g migration addBalanceToRegisters balance:float

rails g migration addBalanceToRegisters balance:float

Then start migraation to add the field to registers table rake db:migrate

然后启动migraation将字段添加到寄存器表rake db:migrate

But field balance will be empty, now you have to populate it.

但是场地平衡将是空的,现在你必须填充它。

You could create rake task for this.

你可以为此创建rake任务。

Inside lib/tasks/ folder add new file registers.rake.

在lib / tasks /文件夹中添加新文件registers.rake。

Inside registers.rake add folowing code:

在registers.rake里面添加以下代码:

namespace :registers do
  desc "populate registers balance with appropriate balance amount"
  task :sync_balance => :environment do
    Register.all.each do |r|
      b = r.course.price - r.amount_paid
      r.update balance: b
    end
  end
end

Then run this rake task, like

然后运行这个rake任务,就像

rake registers:sync_balance

#1


You can add the field to registers table, then populate it with appropriate values.

您可以将该字段添加到register表,然后使用适当的值填充它。

First you add field with new migration

首先,使用新迁移添加字段

rails g migration addBalanceToRegisters balance:float

rails g migration addBalanceToRegisters balance:float

Then start migraation to add the field to registers table rake db:migrate

然后启动migraation将字段添加到寄存器表rake db:migrate

But field balance will be empty, now you have to populate it.

但是场地平衡将是空的,现在你必须填充它。

You could create rake task for this.

你可以为此创建rake任务。

Inside lib/tasks/ folder add new file registers.rake.

在lib / tasks /文件夹中添加新文件registers.rake。

Inside registers.rake add folowing code:

在registers.rake里面添加以下代码:

namespace :registers do
  desc "populate registers balance with appropriate balance amount"
  task :sync_balance => :environment do
    Register.all.each do |r|
      b = r.course.price - r.amount_paid
      r.update balance: b
    end
  end
end

Then run this rake task, like

然后运行这个rake任务,就像

rake registers:sync_balance