Having trouble with accepting nested attributes when I've changed the class name. I'm sure I am just missing something obvious but just can't seem to find it.
models/walk.rb
class Walk < ApplicationRecord
has_many :attendees, class_name: 'WalkAttendee', foreign_key: "walk_id", dependent: :destroy
validate :has_attendees
accepts_nested_attributes_for :attendees
def has_attendees
errors.add(:base, 'must add at least one attendee') if self.attendees.blank?
end
end
models/walk_attendee.rb
class WalkAttendee < ApplicationRecord
belongs_to :walk
end
test/models/walk_test.rb
class WalkTest < ActiveSupport::TestCase
test 'walk can be created' do
walk = Walk.new(walk_params)
assert walk.save
end
private
def walk_params
{
title: 'Rideau Walk',
attendees_attributes: [
{ name: 'John Doe', email: 'john-doe@test.ca', phone: '123-321-1234', role: :guide },
{ name: 'Jane Doe', email: 'jane-doe@test.ca', phone: '123-321-1234', role: :marshal }
]
}
end
end
I was going about the validation all wrong. Thanks to @max and @TarynEast for the push in the right direction.
validates :attendees, length: { minimum: 1 }
Did the trick. Didn't know this validation existed. :D