Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy polymorphic association doesn't work for STI if type column of the polymorphic association doesn't point to the base model of STI?
    primarykey
    data
    text
    <p>I have a case of polymorphic association and STI here.</p> <pre><code># app/models/car.rb class Car &lt; ActiveRecord::Base belongs_to :borrowable, :polymorphic =&gt; true end # app/models/staff.rb class Staff &lt; ActiveRecord::Base has_one :car, :as =&gt; :borrowable, :dependent =&gt; :destroy end # app/models/guard.rb class Guard &lt; Staff end </code></pre> <p>In order for the polymorphic assocation to work, according to the API documentation on Polymorphic Assocation, <a href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations" rel="noreferrer">http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations</a> that I have to set <code>borrowable_type</code> to the <code>base_class</code>of STI models, that is in my case is <code>Staff</code>. </p> <p><strong>The question is: Why doesn't it work if the <code>borrowable_type</code> set to STI class?</strong></p> <p>Some test to prove it:</p> <pre><code># 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 &lt; 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 </code></pre> <p>But it seems to be true only with <strong>Staff</strong> instance. The results are:</p> <pre><code># 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. &lt;1&gt; expected but was &lt;2&gt;. </code></pre> <p>Thanks</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload