使用class_name接受嵌套属性

问题描述 投票:0回答:1

我在更改类名时无法接受嵌套属性。我确信我只是遗漏了一些明显但却无法找到它的东西。

车型/ 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
ruby-on-rails nested-attributes accepts-nested-attributes
1个回答
1
投票

我的验证都错了。感谢@max和@TarynEast推动正确的方向发展。

validates :attendees, length: { minimum: 1 }

诀窍。不知道这种验证是否存在。 :d

© www.soinside.com 2019 - 2024. All rights reserved.