驗證我想知道是否有一種方法做STI的update_attributes方法時,驗證基於新類類型的屬性?Rails的STI子類上update_attributes方法
例如,假設我有:
class A < ActiveRecord::Base
end
class B < A
validates :attribute_z, :presence => true
end
class C < A
validates :attribute_x, :presence => true
validates :attribute_y, :presence => true
end
我辦(軌道的方式實現):
b = A.find('b-id')
b.update_attributes({ 'type' => 'C', :attribute_x => 'present', :attribute_y => 'present', :attribute_z => nil }) # will return false with errors on 'attribute_z must be present'
我試着#becomes:
b = A.find('b-id')
b = b.becomes(C)
b.update_attributes({ 'type' => 'C', :attribute_x => 'present', :attribute_y => 'present', :attribute_z => nil })
# this works partially, because the validations are ok but when i look to console i get something like:
UPDATE "as" SET "type" = 'c', "attribute_z" = NULL, "attribute_y' = 'present', 'attribute_x' = 'present' WHERE "as"."type" IN ('C') AND "as"."id" = 'b-id'
# which is terrible because it's looking for a record of B type on the C types.
我可以把:如果=> PROC {|記錄| record.type =='C'}驗證並將驗證放在A類。但是擁有這個子類是沒有意義的。 B和C的基本差別僅在驗證行爲中。 (我對這兩種類型都有很多驗證) – Guilherme