开发者

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:

  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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜