【问题标题】:Rails 5: update nested attributes through another modelRails 5:通过另一个模型更新嵌套属性
【发布时间】:2017-02-01 19:02:27
【问题描述】:

我无法通过第三个模型更新与当前模型相关的嵌套属性。

重点模型:简介

class Profile < ApplicationRecord
  belongs_to :user
  has_many :phone_numbers

  ##Set nested attributes
  accepts_nested_attributes_for :phone_numbers, reject_if: :all_blank, allow_destroy: true

网络属性:电话号码

class PhoneNumber < ApplicationRecord
  belongs_to :profile
end

第三个模型:用户

class User < ApplicationRecord
  has_one :profile
end

在数据库中他们的关系是profile.user_id = user.id, phone_number.user_id = user.id

问题:我如何在更新个人资料时更新电话号码?

我试过了

<%= form_for @profile, url: {action: "update"} do |f| %>
 ...
     <%= f.fields_for :phone_numbers do |ff| %>
       ...

并收到错误消息:

Mysql2::Error: 'where'中的未知列'phone_numbers.profile_id' 子句': SELECT phone_numbers.* FROM phone_numbers WHERE phone_numbers.profile_id = 1

【问题讨论】:

  • 我知道,您从未接受任何问题的答案。这是该站点的规则之一 - 您选择一个来通知用户问题已解决。确保在您的问题(问题中陈述的第一个问题)得到解答时接受答案。

标签: mysql ruby-on-rails


【解决方案1】:

要将profile_id 列添加到phone_numbers 表,您需要迁移。这是使用 rails 命令执行的,如下所示:

rails generate migration AddProfileRefToPhoneNumbers  profile:references
rake db:migrate

这将解决您的错误问题。我还可以看到您会遇到问题:

class User < ApplicationRecord
  has_one :profile
end
class Profile < ApplicationRecord
  belongs_to :account

您的个人资料属于帐户,而不是用户。您想用用户替换帐户或用 account_id 替换您的外键并将行更改为:

  belongs_to :account, class_name: 'User'

【讨论】:

    【解决方案2】:

    错误非常清晰且充满号召性用语:

    • profile_id 列添加到phone_numbers 表以反映ProfilePhoneNumber 模型之间的关联。

    【讨论】:

    • 现在 ProfilePhoneNumber 没有直接关系,但它们引用的是 user.id。有没有办法通过使用 shared(user.id) 而不添加新列来解决问题?
    • @Alex 澄清了这个问题。但是在programmin中真的没有什么是不可能的
    猜你喜欢
    • 2019-08-16
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多