How to update existing nested attribute w/ no FK
-
30-09-2019 - |
Question
Assuming User has_one :subscription, Subscription belongs_to :user, and I am using accepts_nested_attributes_for to nest subscription attributes into the user creation form, what is the best way to locate and update and existing subscription (if it exists) based on User.email == Subscription.email?
Note that existing subscriptions could have user_id = nil
Solution
Probably what you want to do is use the email as the foreign key:
class User < ActiveRecord::Base
has_one :subscription, :foreign_key => "email", :primary_key => "email"
end
OTHER TIPS
I would imagine that this would need to be split into a two-step process:
- Locate the user you want to update.
- Locate a subscription (if any) with the user's e-mail address, Set the subscription on the user to this record.
- Update the user as normal. Since the association is now present (i.e. user.subscription will not be nil), the subscription records will update correctly.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow