Hi,
I have been battling something for a good hour and a half and finally realized how to 'solve' the issue but I am very confused as of why I should do what I just did.
I have 2 classes:
class User has_many :audits ... end
class Audit belongs_to :user ... end
The way things need to work is to first create an audit and after the audit is created a user that has access to the audit gets created. This has to work this way and not the other way around.
I have been testing my code in the console with the following:
audit = Audit.create(...) audit.create_user(...)
In all instances 'audit' ended up being updated correctly with the user ID.
However, when I executed a very similar code in my controller I got different results.
My original control code: @audit = Audit.new(params[:audit]) ... if @audit.save @audit.create_user(...) unless @audit.tenant_id # this code is never hit end end
Everything seems OK since the @audit.tenant_id seemed to have a value but when the code was done running the database showed that the user was created but the audit never got updated with the user ID. In order to make it work I had to modify the code above as:
@audit = Audit.new(params[:audit]) ... if @audit.save @audit.create_user(...) @audit.save # <------- Why do I need to do this? unless @audit.tenant_id # this code is never hit end end
I am very confused because the console updates the audit record but the controller doesn't.
??? Why ???
I'd appreciate an explanation of the difference in behavior.
Thank you.