保存没有引用 id 的活动记录对象

Save active record object without reference id

我有以下迁移:

 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 模型中,只需添加 optional 参数即可使其工作:

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

默认情况下,rails设置为true,所以用false代替,详细说明here