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

Was it helpful?

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:

  1. Locate the user you want to update.
  2. Locate a subscription (if any) with the user's e-mail address, Set the subscription on the user to this record.
  3. 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
scroll top