I am having trouble saving objects to their corresponding tables.
Model Customer. I want to make sure it has an associated valid Account:
has_one :account, dependent: :destroy
validates_presence_of :account
validates_associated :account
Model Account belongs to Customer, so I want to enforce customer_id is present:
belongs_to :customer
validates :customer_id, presence: true
Now, my question is: Which order should I save these objects? Are these validations somewhat incompatible?
Because, if I try to save Customer first, it won't be possible, I will get
myCustomer.save.errors.messages
{:account=>["can't be blank"]}
Obviously, since I stated
validates_presence_of :account
in the model.
But if I try to save Account first, wait! I can't save it either! I have
validates :customer_id, presence: true
in my Account model and I haven't saved any customer yet !
So I have also tried to just initialize the Account:
acc = Account.new(acc_attr: foo, acc_attr2: bar)
and then try to set it to Customer like this
Customer.account = acc
But then again, customer won't save since acc is not valid, (since it doesn't have a customer_id and I have validates_associated :account in the Customer model)
So, will I have to give up on one validation in either model? Is there a workaround for this?
Thanks!