【问题标题】:ActiveRecord belongs_to association does not save foreign_key (Rails 4)ActiveRecord belongs_to 关联不保存 foreign_key (Rails 4)
【发布时间】:2013-07-08 07:57:52
【问题描述】:

这个周末我决定试一试 Rails 4,但很快就遇到了以下问题:

我有两个模型(想试试 OpenSchema,以防您想知道):

记录

has_many :ns_attributes

NsAttribute

belongs_to :record

现在在控制台中:

record = Record.create!(name: "blowing in the wind")
nsa = NsAttribute.new(key: "artist", value: "bob dylan", record: record)


#<NsAttribute id: nil, key: "artist", value: "bob dylan", record_id: 4, created_at: nil, updated_at: nil>

irb(main):007:0> nsa.save!
(0.4ms)  BEGIN
Record Exists (0.7ms)  SELECT 1 AS one FROM "records" WHERE "records"."name" IS NULL LIMIT 1
(0.2ms)  COMMIT
=> true
irb(main):008:0> nsa
=> #<NsAttribute id: nil, key: "artist", value: "bob dylan", record_id: nil, created_at: nil, updated_at: nil>

如您所见,记录未保存(record_id: nil)。

  • 我还尝试将 class_name 和 foreign_key 添加到 belongs_to 方法而不做任何更改。
  • 可能是因为 AR 型号名称的原因吗? (“记录”)
  • 这两个模型没有验证

感谢您提供任何有关正在发生的事情的线索!

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-4


    【解决方案1】:

    我也遇到了同样的问题。这似乎是 Rails 4 中的一个错误。这是测试用例:

    https://gist.github.com/jemmyw/8163504

    这就是问题所在:

    https://github.com/rails/rails/issues/13522

    您可以通过在具有记录关联的模型下方添加以下 sn-p 来针对每个模型修复它:

    NsAttribute::GeneratedFeatureMethods.module_eval %Q{
      def create_record(*args, &block)
        super
      end
    }
    

    【讨论】:

    • 嗨@Jeremy!感谢您的回答,我认为将列命名为“记录”有问题,但从未进一步调查(只是重命名)。谢谢你告诉我!
    【解决方案2】:

    试试这个:

    record.ns_attributes.create!(key: "artist", value: "bob dylan")
    

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多