Reputation: 13
Please I am new to Rails. I want to populate a model database table from another model form. I have a customer model and form and I want to save the form data into the customer database table and also add data to another customer account database table. The customer fields are
Name, Address, Phone, Current_balance, Outstanding_balance.
Customer account fields, customer name, transaction date, balance, mode of payment
Below is my code but I cannot seem to solve the problem.
Customer model
class Customer < ApplicationRecord
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
end
Customer Account model
class CustomerAccount < ApplicationRecord
belongs_to :customer
end
What how do I get it done
Upvotes: 0
Views: 679
Reputation: 81
I'm not a huge fan of after_create callback.
Just try to put the method call inside the if @customer.save inside the create action.
if @customer.save
add_customer_account <---------
format.html {render ..... blabla
else
...
end
The second thing that i see is that you're putting this code inside the Model, try to keep the business logic inside the controller.
Try to define the add_customer_account under private inside the customers_controller, and then call it as i mentioned before.
Use the method from the Jhumur Chatterjee and put a byebug just before the b.save! action. Then in the console you can just do b.errors.messages
Upvotes: 0
Reputation: 64
you can try like this:
# 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
Upvotes: 1