When we declare a
belongs_to association, the declaring class automatically
For example, given the declaration:
Each instance of the Book model will have
Now let’s consider the following models.
To create a supplier account, we can call
create_account on the Supplier object as shown below:
The direct association of
has_one: :account works as expected.
But when we try to create AccountHistory, we get the below error:
As we can see, the
create_account_history method is missing when we created the
has_one :through relationship.
Before Rails 7,
to fix the above issue,
we can add a method
create_account_history to the
This change works as expected, but we would end up writing similar methods
for all our
has_one :through associations.
To resolve the above issue,
create_association on has_one :through associations.
AccountHistory can be created via Supplier object as shown below.
build_account_history will work and, it will not throw a