3
使用Rails 5.0.0.rc1,我無法獲得「驗證」選項來處理HABTM關聯。我認爲「驗證:false」的意思是告訴導軌在父對象保存時不要驗證關聯的對象。所以,這是我想要的行爲 - 我不想驗證組件保存時的相關零件。我究竟做錯了什麼?謝謝你的幫助!爲什麼HABTM上的「驗證」選項不起作用?
編輯:我試着用軌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個驗證的部分模型重新創建我的問題(導軌控制檯如下):
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'