ここでは、多型関連とSTIの症例があります。多型assocationが動作するためには多型関連の型の列がSTIの基本モデルを指していない場合、多型関連が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
、私はSTIモデルのbase_class
にborrowable_type
を設定する必要が多形Assocation、http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+AssociationsのAPIドキュメントによると、それは私の場合ですが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>.
おかげ
つまり、Carテーブルは常に 'borrowable_type'列が 'Staff'に設定され、Guardには決して送られないため、CarとGuardを関連付けることはできず、 '@ guard.car'で取得することはできません。そしてそれは、STIモデル上の多型関連が完全に役に立たないことを意味します。 – dekeguard
これは私のために働いた可能性があります。うーん...それはボックスの外で動作しないことは奇妙です。私は理由を見ることができません。 – Macario
リンクと説明のための+1 ... –