Understanding optional: true in one-to-many relationship in Rails 5

0

It has a one-to-many relationship and I can only create a child object if you use optional: true. I know it solves but I do not understand the need!

In my seeds.rb I have a block of type

3.times do |n|
  Parent.last.children.create!(
    name: "Child #{n}"
  )
end

Without using optional, the RecordInvalid module says that Parent must exist! Is Parent.last no longer a valid object?

Optional: true mean that I can create Child without Parent? This is not what I want to have in my application!

class Child < ApplicationRecord
  belongs_to :parent, optional: true
end

class Parent < ApplicationRecord
  has_many :children
  validate_presence_of :name, :last_name
end
    
asked by anonymous 05.08.2018 / 04:44

0 answers