即使 rails 中的相关列为空,我也希望能够存储值

I want to be able to store values even if the related column is empty in rails

我们想要实现的目标

我正在 Rails 中进行关联,我正在将日程表 table 与 PostItem table 关联,并且我正在将 PostItem 与 belongs_to 在 Schedule table 中,即使在 Schedule table 中与它关联的 PostItem_id 是空的。我希望能够保存文件。换句话说,我不想每次都联想;当我在迁移中建立关联时,我总是需要 PostItem_id 。有什么方法可以在关联的父级为空的情况下进行保存吗?

代码

迁移文件


class CreateSchedules < ActiveRecord::Migration[6.0]
  def change
    create_table :schedules do |t|
      t.string :name
      t.string :color
      t.integer :start
      t.integer :end
      t.boolean :timed
      t.boolean :long_time
      t.integer :postItem_id # I want to save the file even if it is empty.

      t.timestamps
    end
  end
end

排程模型

class Schedule < ApplicationRecord
  belongs_to :post_item
    validates :start, presence: true
    validates :end, presence: true
    # validates :postItem_id, allow_nill: true, allow_blank: true
end

postItem 模型


class PostItem < ApplicationRecord
  belongs_to :post
  has_many :schedules
end

在Rails之后默认需要5个belongs_to关联。如果你希望它是可选的,你可以添加 optional: true.

belongs_to :post_item, optional: true

您还可以通过执行以下操作更改每个模型的此行为:

self.belongs_to_required_by_default = false

https://guides.rubyonrails.org/upgrading_ruby_on_rails.html#active-record-belongs-to-required-by-default-option