接受 class_name 的嵌套属性

Accept Nested Attributes with class_name

更改 class 名称后无法接受嵌套属性。我确定我只是遗漏了一些明显的东西,但似乎找不到它。

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

测试/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

我在进行验证时完全错了。感谢@max 和@TarynEast 在正确方向上的推动。

validates :attendees, length: { minimum: 1 }

成功了。不知道这个验证存在。 :D

如果像我一样,其他人因为面临嵌套属性和 has_many 关系的问题(Rails 5.2 / Rails 6)而到达此线程,我的问题已通过使用 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 关系来修复它:

has_many :lines, inverse_of: "price_list", foreign_key: "price_list_id", class_name: "PriceListLine", dependent: :destroy