在我更改了班级名称时,无法接受嵌套属性。我确定我只是遗漏了一些明显但却无法找到它的东西。
模型/ 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
答案 0 :(得分:1)
我正在进行验证错误。感谢@max和@TarynEast推动正确的方向。
validates :attendees, length: { minimum: 1 }
诀窍。不知道这种验证是否存在。 :d
答案 1 :(得分:0)
如果像我一样,其他人因为面临嵌套属性和 has_many
关系(使用 Rails 5.2 / Rails 6)的问题而访问此线程,我的问题已通过使用 {{1 }}:
我最初的问题:
inverse_of
我通过将 class PriceList
has_many :lines, foreign_key: "price_list_id", class_name: "PriceListLine", dependent: :destroy
accepts_nested_attributes_for :lines, allow_destroy: true
end
class PriceListLine
belongs_to :price_list
end
PriceList.new(lines: [{..}]).valid?
# --> false. Error = price_list_line.attributes.price_list.required
添加到 inverse_of: "price_list"
关系来修复它:
has_many