Ruby on rails 从rubyonrails中的另一个模型表单创建后,自动将数据添加到另一个模型数据库表

Ruby on rails 从rubyonrails中的另一个模型表单创建后,自动将数据添加到另一个模型数据库表,ruby-on-rails,Ruby On Rails,拜托,我是Rails的新手。我想从另一个模型表单填充模型数据库表。我有一个客户模型和表单,我想将表单数据保存到客户数据库表中,并将数据添加到另一个客户帐户数据库表中。客户字段是 名字, 地址:, 电话, 当前余额, 未清余额 客户账户字段, 客户名称, 交易日期, 平衡, 付款方式 下面是我的代码,但我似乎无法解决问题 客户模型 类客户

拜托,我是Rails的新手。我想从另一个模型表单填充模型数据库表。我有一个客户模型和表单,我想将表单数据保存到客户数据库表中,并将数据添加到另一个客户帐户数据库表中。客户字段是

名字, 地址:, 电话, 当前余额, 未清余额

客户账户字段, 客户名称, 交易日期, 平衡, 付款方式

下面是我的代码,但我似乎无法解决问题

客户模型

类客户<应用程序记录

after_create :add_customer_account 

has_many :customer_accounts 

def add_customer_account
  b= CustomerAccount.new
  b.transaction_date = Customer.created_at
  b.balance = Customer.current_balance.to_i - Customer.outstanding_balance.to_i
  b.customer_id = Customer.id
  b.invoice = "0"
  b.create
end
belongs_to :customer
结束

客户账户模式

类CustomerAccount<应用程序记录

after_create :add_customer_account 

has_many :customer_accounts 

def add_customer_account
  b= CustomerAccount.new
  b.transaction_date = Customer.created_at
  b.balance = Customer.current_balance.to_i - Customer.outstanding_balance.to_i
  b.customer_id = Customer.id
  b.invoice = "0"
  b.create
end
belongs_to :customer
结束

我如何完成它

您可以这样尝试:

# app/models/customer.rb

class Customer < ApplicationRecord
  after_create :add_customer_account 

  has_many :customer_accounts 

  def add_customer_account
    b = customer_accounts.new
    b.transaction_date = self.created_at
    b.balance = self.balance
    b.invoice = "0"
    b.save!
  end

  def balance
    (current_balance - outstanding_balance).to_i
  end
end
#app/models/customer.rb
类客户<应用程序记录
创建后:添加客户帐户
拥有多个客户账户
def添加客户账户
b=客户账户。新
b、 交易日=自创建日
b、 平衡
b、 发票=“0”
b、 救命!
结束
def平衡
(当前余额-未清余额)。至
结束
结束

我不太喜欢创建后回调

只需尝试将方法调用放在创建操作中的if@customer.save中

  if @customer.save
    add_customer_account       <---------
    format.html {render ..... blabla
  else
    ...
  end
if@customer.save

添加客户帐户谢谢朱穆尔·查特吉。我会试试这个并给出回应。你好,朱穆尔·查特吉,再次感谢。添加代码后,formis不会添加到数据库中。从终端,我看到事务回滚。我认为这个过程不起作用。有更好的方法吗?请我需要帮助,它没有被创建。从我的终端,我得到了事务回滚,感谢Toni Saez valls和Jhumur Chatterjee。我可以用你的流程完成。我在customer controller中添加了add_customer_account类,这两个数据库表都被填充了。很高兴听到这个消息!