1

我想知道是否有办法在执行 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

如果我运行(实现 rails 的方式):

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.
4

2 回答 2

0

与此主题相关联回调更改的 ActiveRecord 属性?,您可以使用 become 方法捕获对 type 属性所做的任何分配并使“self”属于不同的类(A、B 或 C)。因此,每当您使用 find 方法时,它都会使用来自数据库的数据(由“b-id”标识)填充一个全新的模型实例,并在必要时自动将模型实例强制转换为另一种类型。

这对你有帮助吗?

于 2013-01-14T18:12:18.953 回答
0

我制定了一个解决方案:https ://gist.github.com/4532583 ,因为条件是由 rails 内部添加的(https://github.com/rails/rails/blob/master/activerecord/lib/active_record/继承.rb#L15)我创建了一个新的“update_attributes”方法,如果给定类型,它会更改类型。:)

于 2013-01-14T22:51:12.573 回答