我在更改类名时无法接受嵌套属性。我确信我只是遗漏了一些明显但却无法找到它的东西。
车型/ 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: '[email protected]', phone: '123-321-1234', role: :guide },
{ name: 'Jane Doe', email: '[email protected]', phone: '123-321-1234', role: :marshal }
]
}
end
end
我的验证都错了。感谢@max和@TarynEast推动正确的方向发展。
validates :attendees, length: { minimum: 1 }
诀窍。不知道这种验证是否存在。 :d