gpt4 book ai didi

ruby-on-rails - 如果多态关联的类型列不指向 STI 的基本模型,为什么多态关联对 STI 不起作用?

转载 作者:行者123 更新时间:2023-12-04 04:43:47 25 4
gpt4 key购买 nike

我这里有一个多态关联和 STI 的案例。

# app/models/car.rb
class Car < ActiveRecord::Base
belongs_to :borrowable, :polymorphic => true
end

# app/models/staff.rb
class Staff < ActiveRecord::Base
has_one :car, :as => :borrowable, :dependent => :destroy
end

# app/models/guard.rb
class Guard < Staff
end

为了使多态关联工作,根据关于多态关联的 API 文档, http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations我必须设置 borrowable_typebase_class STI 模型,在我的情况下是 Staff .

问题是:如果 borrowable_type 为什么它不起作用?设置为 STI 类?

一些测试来证明它:
# now the test speaks only truth

# test/fixtures/cars.yml
one:
name: Enzo
borrowable: staff (Staff)

two:
name: Mustang
borrowable: guard (Guard)

# test/fixtures/staffs.yml
staff:
name: Jullia Gillard

guard:
name: Joni Bravo
type: Guard

# test/units/car_test.rb

require 'test_helper'

class CarTest < ActiveSupport::TestCase
setup do
@staff = staffs(:staff)
@guard = staffs(:guard)
end

test "should be destroyed if an associated staff is destroyed" do
assert_difference('Car.count', -1) do
@staff.destroy
end
end

test "should be destroyed if an associated guard is destroyed" do
assert_difference('Car.count', -1) do
@guard.destroy
end
end

end

但似乎只有 才是正确的员工 实例。结果是:
# Running tests:

F.

Finished tests in 0.146657s, 13.6373 tests/s, 13.6373 assertions/s.

1) Failure:
test_should_be_destroyed_if_an_associated_guard_is_destroyed(CarTest) [/private/tmp/guineapig/test/unit/car_test.rb:16]:
"Car.count" didn't change by -1.
<1> expected but was
<2>.

谢谢

最佳答案

好问题。我在使用 Rails 3.1 时遇到了完全相同的问题。看起来你不能这样做,因为它不起作用。可能这是一种预期的行为。显然,在 Rails 中使用多态关联和单表继承 (STI) 有点复杂。

当前 Rails 3.2 的 Rails 文档给出了合并 polymorphic associations and STI 的建议:

Using polymorphic associations in combination with single table inheritance (STI) is a little tricky. In order for the associations to work as expected, ensure that you store the base model for the STI models in the type column of the polymorphic association.



在您的情况下,基本模型将是“Staff”,即“borrowable_type”对于所有项目都应该是“Staff”,而不是“Guard”。可以使用“becomes”使派生类显示为基类: guard.becomes(Staff) .可以将列“borrowable_type”直接设置为基类“Staff”,或者按照 Rails 文档的建议,使用自动转换它
class Car < ActiveRecord::Base
..
def borrowable_type=(sType)
super(sType.to_s.classify.constantize.base_class.to_s)
end

关于ruby-on-rails - 如果多态关联的类型列不指向 STI 的基本模型,为什么多态关联对 STI 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9628610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com