使用class_name接受嵌套属性

时间:2023-01-09 10:57:19

Having trouble with accepting nested attributes when I've changed the class name. I'm sure I am just missing something obvious but just can't seem to find it.

我在更改类名时遇到嵌套属性的问题。我确信我只是遗漏了一些明显的东西,但似乎无法找到它。

models/walk.rb

车型/ 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

车型/ walk_attendee.rb

class WalkAttendee < ApplicationRecord
  belongs_to :walk
end

test/models/walk_test.rb

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

1 个解决方案

#1


1  

I was going about the validation all wrong. Thanks to @max and @TarynEast for the push in the right direction.

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

validates :attendees, length: { minimum: 1 }

Did the trick. Didn't know this validation existed. :D

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

#1


1  

I was going about the validation all wrong. Thanks to @max and @TarynEast for the push in the right direction.

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

validates :attendees, length: { minimum: 1 }

Did the trick. Didn't know this validation existed. :D

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