简体   繁体   中英

How do i add a summation column to my table on Rails 4

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 .

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

so I tried

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

but when I try

rake db:migrate

I get an error

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

First you add field with new migration

rails g migration addBalanceToRegisters balance:float

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

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

You could create rake task for this.

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

Inside registers.rake add folowing code:

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 registers:sync_balance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM