【问题标题】:Save active record object without reference id保存没有参考 ID 的活动记录对象
【发布时间】:2016-10-12 03:58:26
【问题描述】:

我有以下迁移:

 class CreateMothers < ActiveRecord::Migration[5.0]
       def change
         create_table :mothers do |t|
           t.string :name

           t.timestamps
         end
       end
     end

和:

class CreateSons < ActiveRecord::Migration[5.0]
   def change
     create_table :sons do |t|
       t.string :name
       t.references :mother

       t.timestamps
     end
   end
 end

每当我尝试将 Mother_id 字段为空白的 Son 对象保存时,我都会收到错误消息:“Mother must exist”

有没有办法在没有mother_id 字段的情况下保存它?

【问题讨论】:

  • 您是否有验证来检查您的Son 模型中是否存在mother_id?如果是这样,您需要删除该验证以将 Son 对象保存为 mother_id 字段为空白。
  • 没有验证。但是当我从 Son 模型中删除 belongs_to :mother 时,它工作得很好。

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


【解决方案1】:

在您的 Son 模型中,只需添加 optional 参数即可使其工作:

class Son < ApplicationRecord
  belongs_to :mother, optional: true
end

默认情况下,rails 将其设置为true,因此请改用false,详细描述here

【讨论】:

  • 非常感谢!你真是个天才。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-18
  • 1970-01-01
  • 2013-06-03
  • 1970-01-01
相关资源
最近更新 更多