Telmo Gonçalves
Telmo Gonçalves

Reputation: 21

Rails Relations

I've 3 tables:

profiles, users, payment_details

Now, in models/user.rb I've the following:

has_one :profile, :dependent => :destroy
has_one :payment_detail, :dependent => :destroy

In models/profile.rb I have:

has_one :payment_detail, :through => :user

And in models/payment_details.rb I have:

has_one :profile, :through => :user

Then I have a :profile form with a :payment_details nested form.

For some reason the :payment_details gets the :user_id updated with the :id from :profiles instead of the :user_id from :profiles

Upvotes: 0

Views: 118

Answers (1)

cdesrosiers
cdesrosiers

Reputation: 8892

Based on the documentation, the behavior of accepts_nested_attributes_for doesn't seem to be well-defined for :through associations. The relationship is generally assumed to be direct parent-child, so it's not surprising that you would see odd behavior like this.

You should either handle the form through the User model, accepting attributes for the PaymentDetail model, or combine your models in some way. I rarely find it useful to use has_one associations, because the cost of maintaining them tend to outweigh benefits, but it always depends on your use case. If you don't have too many columns, you might want to combine User with Profile, and maybe with PaymentDetail to simplify your code.

Upvotes: 1

Related Questions