更改类名后无法接受嵌套属性。我确定我只是错过了一些明显的东西,但似乎找不到它。
模型/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
模型/walk_attendee.rb
class WalkAttendee < ApplicationRecord
belongs_to :walk
end
测试/模型/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