【问题标题】:Rails RelationsRails 关系
【发布时间】:2012-11-11 02:57:28
【问题描述】:

我有 3 张桌子:

profiles, users, payment_details

现在,在models/user.rb 我有以下内容:

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

models/profile.rb 我有:

has_one :payment_detail, :through => :user

models/payment_details.rb 我有:

has_one :profile, :through => :user

然后我有一个 :profile 表单和一个 :payment_details 嵌套表单。

由于某种原因,:payment_details 使用来自 :profiles:id 而不是来自 :profiles:user_id 更新了 :user_id

【问题讨论】:

  • 您似乎缺少每个关系的belongs_to 方面。这只是复制粘贴的遗漏吗?
  • 是的,我在payment_detailprofile 模型中都有belongs_to :user
  • 给我们一个带有表单和控制器的视图。

标签: ruby-on-rails activerecord database-relations


【解决方案1】:

根据文档,accepts_nested_attributes_for 的行为似乎对:through 关联没有明确定义。这种关系通常被认为是直接的父子关系,因此您会看到这样的奇怪行为也就不足为奇了。

您应该通过User 模型处理表单,接受PaymentDetail 模型的属性,或者以某种方式组合您的模型。我很少发现使用has_one 关联很有用,因为维护它们的成本往往超过收益,但这始终取决于您的用例。如果您没有太多的列,您可能希望将UserProfile 组合在一起,或者与PaymentDetail 组合以简化您的代码。

【讨论】:

  • 我会尝试不同的方式。我将直接将PaymentDetail 保存在Profile 控制器上,而不是嵌套路由。我试图在你的答案中投票,但我没有足够的声誉,抱歉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多