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: '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
4

2 回答 2

1

我要进行验证都错了。感谢@max 和@TarynEast 朝着正确的方向前进。

validates :attendees, length: { minimum: 1 }

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

于 2018-03-05T02:21:10.633 回答
0

如果像我一样,其他人因为遇到嵌套属性和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
于 2021-06-24T20:57:47.773 回答