How to update existing nested attribute w/ no FK
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 U开发者_StackOverflowser.email == Subscription.email?
Note that existing subscriptions could have user_id = nil
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
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.
精彩评论