为什么没有"验证"关于HABTM工作的选择?

时间:2016-06-08 03:27:31

标签: ruby-on-rails validation activerecord ruby-on-rails-5

使用 Rails 5.0.0.rc1 ,我无法获得"验证"处理HABTM关联的选项。我想到了"验证:false"是告诉rails在保存父对象时不要验证关联的对象。所以,这是我想要的行为 - 我不想在保存程序集时验证相关的部件。我究竟做错了什么?谢谢你的帮助!

编辑:我尝试使用 rails 4.2.6 这个相同的示例,我可以更改程序集的part_ids而不会出现验证错误。但是,使用" validate:false"在装配模型上没有任何效果......即使我在关联上有无效的零件对象,它也能正常工作。

这是我的榜样:

class Assembly < ApplicationRecord
  has_and_belongs_to_many :parts, validate: false
end
class Part < ApplicationRecord
  validates :name, presence: true
  validates :serial_number, presence: true
  has_and_belongs_to_many :assemblies
end
ActiveRecord::Schema.define(version: 20160608024352) do

  create_table "assemblies", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "assemblies_parts", id: false, force: :cascade do |t|
    t.integer "assembly_id", null: false
    t.integer "part_id",     null: false
    t.index ["assembly_id"], name: "index_assemblies_parts_on_assembly_id"
    t.index ["part_id"], name: "index_assemblies_parts_on_part_id"
  end

  create_table "parts", force: :cascade do |t|
    t.string   "name"
    t.string   "serial_number"
    t.datetime "created_at",    null: false
    t.datetime "updated_at",    null: false
  end

end

我在数据库中创建了一些零件和装配体,然后将2个验证添加到零件模型中以重新创建我的问题(跟随rails控制台):

Loading development environment (Rails 5.0.0.rc1)
irb(main):001:0> a = Assembly.first
Assembly Load (0.2ms)  SELECT  "assemblies".* FROM "assemblies" ORDER BY "assemblies"."id" ASC LIMIT ?  [["LIMIT", 1]]
=> #<Assembly id: 1, name: "stage 1", created_at: "2016-06-08 02:46:59", updated_at: "2016-06-08 02:46:59">
irb(main):002:0> a.part_ids
   (0.2ms)  SELECT "parts".id FROM "parts" INNER JOIN "assemblies_parts" ON "parts"."id" = "assemblies_parts"."part_id" WHERE "assemblies_parts"."assembly_id" = ?  [["assembly_id", 1]]
=> [1, 2]
irb(main):003:0> a.part_ids = [2,3]
  Part Load (0.3ms)  SELECT "parts".* FROM "parts" WHERE "parts"."id" IN (2, 3)
  Part Load (0.2ms)  SELECT "parts".* FROM "parts" INNER JOIN "assemblies_parts" ON "parts"."id" = "assemblies_parts"."part_id" WHERE "assemblies_parts"."assembly_id" = ?  [["assembly_id", 1]]
   (0.1ms)  begin transaction
  SQL (1.1ms)  DELETE FROM "assemblies_parts" WHERE "assemblies_parts"."assembly_id" = ? AND "assemblies_parts"."part_id" = 1  [["assembly_id", 1]]
   (3.1ms)  rollback transaction
ActiveRecord::RecordInvalid: Validation failed: Serial number can't be blank
    from /Users/lsmith/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activerecord-5.0.0.rc1/lib/active_record/validations.rb:78:in `raise_validation_error'

1 个答案:

答案 0 :(得分:0)

:validate选项仅适用于新记录。如果您尝试添加现有记录,它将始终验证它们。这种行为与Rails 4不同。在github中有一个关于它的讨论 - https://github.com/rails/rails/issues/25718