【问题标题】:Accept Nested Attributes with class_name接受带有 class_name 的嵌套属性
【发布时间】:2018-03-04 21:21:17
【问题描述】:

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

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

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

【问题讨论】:

  • 这是一个难题。您无法保存步行,除非它有任何参加者,并且您不能将任何内容与步行关联,除非它已保存并具有 ID。你需要重新考虑你的方法。 blank? 还用于测试您应该使用的关联和数组的用户输入(字符串)any?
  • 您能否扩展“当我更改班级名称时”...以前是否有效,但自从您更改班级名称后发生了变化?如果有,之前是什么?你确定那是什么破坏了它?因为我对验证持怀疑态度 - 您能否通过暂时删除它并查看它是否正常工作来仔细检查?
  • 呃...感谢@max 的小小推动,@TarynEast blank? 在我的其他一些测试中出现误报。 validates :walk_attendees, length: { minimum: 1 } 是我所需要的。

标签: ruby-on-rails nested-attributes accepts-nested-attributes


【解决方案1】:

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

validates :attendees, length: { minimum: 1 }

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

【讨论】:

    【解决方案2】:

    如果像我一样,其他人因为遇到嵌套属性和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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多