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

Time:03-17

What we want to achieve

I'm doing the association in Rails, I'm associating the Schedule table with the PostItem table, and I'm associating the PostItem with belongs_to in the Schedule table, even if the PostItem_id associated with it in the Schedule table is empty. I would like to be able to save the file. In other words, I don't want to make the association every time; I always need the PostItem_id when I make the association within migration. Is there any way to allow saving even if the associated parent is empty?

Code

Migration File


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

Schedule Model

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 model


class PostItem < ApplicationRecord
  belongs_to :post
  has_many :schedules
end

CodePudding user response:

After Rails 5 belongs_to associations are required by default. If you want it to be optional, you can add optional: true.

belongs_to :post_item, optional: true

You can also change this behaviour per model by doing:

self.belongs_to_required_by_default = false

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

  • Related