如何在保存一个模型之前更新另一个模型的数据

时间:2017-03-22 19:00:29

标签: ruby-on-rails ruby activerecord

我在rails中制作钱包应用程序。我不知道如何在事务中插入新记录之前更新用户模型中的余额字段。 当用户发送资金时user_id取自隐藏字段,并且必须输入电子邮件,并且user_emailamountclass User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :transactions end 存储在交易表中。 如何从一条记录中扣除资金并添加到另一条记录中。我可以使用sql update来做到这一点吗?

这是用户模型

create_table "users", force: :cascade do |t|
 t.string   "email"    
 t.string   "encrypted_password"   
 t.string   "reset_password_token"
 t.datetime "reset_password_sent_at"
 t.datetime "remember_created_at"
 t.integer  "sign_in_count"        
 t.datetime "current_sign_in_at"
 t.datetime "last_sign_in_at"
 t.string   "current_sign_in_ip"
 t.string   "last_sign_in_ip"
 t.datetime "created_at"                         
 t.datetime "updated_at"                      
 t.string   "Firstname"            
 t.string   "Lastname"               
 t.date     "Dob"
t.integer  "Balance"

这是此字段中包含的用户表余额。

class Transaction < ApplicationRecord

     belongs_to :user
end

create_table "transactions", force: :cascade do |t|
  t.integer  "user_id"
  t.string   "user_email"
  t.integer  "amount"
  t.datetime "created_at"
  t.datetime "updated_at"
end

这是交易表。 User_id用于发件人,user_email用于接收者

    function getTime() {

        $.ajax({
            type : 'POST',
            async:  false,
            url  : 'time.php',
            success : function(response){

                // date of button display

                var year = "2017",
                    month = "03",
                    day = "22",
                    hour = "13",
                    minute = "50",
                    second = "01";

                var startDate = new Date("" + year + "-" + month + "-" + day + "T" + hour + ":" + minute + ":" + second +"+01:00"); 

                // +01:00 timezone correction

                var buttonTime = startDate.getTime() / 1000; // time - when display button

                var currentTime = parseInt(response);

                if (!Date.now) {
                  Date.now = function now() {
                    return new Date().getTime() / 1000;
                  };
                }

                var userPcTime = Math.floor(Date.now() / 1000);

                if (currentTime !== userPcTime) {

                    var timeDiff = currentTime - userPcTime;

                    buttonTime = buttonTime - timeDiff;

                    console.log(timeDiff);
                }

                function testTime() {

                    if (!Date.now) {
                      Date.now = function now() {
                        return new Date().getTime() / 1000;
                      };
                    }

                    var userPcTime = Math.floor(Date.now() / 1000);

                     var diff = buttonTime - userPcTime;



                    if (userPcTime > buttonTime ) {
                        // triggers here"

                        alert(' here will be trigger of show button');

                    }

                    if (userPcTime <= buttonTime && diff <= 60 ) {

                        // test after 1 s.

                         var testDelay = 1000;

                        setTimeout(function() {
                            testTime();
                        }, testDelay);
                    }

                    if (userPcTime < buttonTime && diff > 60 ) {
                        // test after 10 s.

                        var testDelay = 10000;

                        setTimeout(function() {
                            testTime(); 
                        }, testDelay);

                    } 

                };

                testTime();

            },
            complete(){},
            error(){}
        });

    };

getTime();

3 个答案:

答案 0 :(得分:2)

您可以使用before_save回调:

class User < ApplicationRecord

  before_save :do_something_transaction

  def do_something_transaction
    #here you update your transanction
  end

end

答案 1 :(得分:2)

您可以尝试使用此代码。用于从用户调用创建交易

current_user.transaction.new(transaction_params)

现在在model transaction.rb文件中

class Transaction < ApplicationRecord
  belongs_to :user
  before_save :check_and_update_balance

  def check_and_update_balance
    ## since user or sender is already there no need of sender
    receiver = User.find_by(email: user_email)
    if user.has_sufficient_balance?(amount) and receiver.present?
       user.update_attributes(balance: balance - amount)
       receiver.update_attributes(balance: balance + amount)    
    end
  end
end

希望这有助于!!

答案 2 :(得分:0)

获取发件人和收件人的余额,如下所示:

@sender = User.find_by(id: user_id)
@receiver = User.find_by(email: user_email)

要更改余额,请使用ActiveRecord update

if @sender.has_sufficient_balance?(amount) # make sure sender has sufficient balance first!
  @sender.update(balance: @sender.balance - amount)
  @receiver.update(balance: @receiver.balance + amount)
end

您可以使用before_save回调,因为Alejandro Montilla建议这样做。

另外,使用decimalamount的{​​{1}}数据类型代替balance