相关疑难解决方法(0)

如果多态关联的类型列不指向STI的基本模型,为什么多态关联不适用于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
Run Code Online (Sandbox Code Playgroud)

为了使多态关联起作用,根据多态关联的API文档,http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations 我必须设置borrowable_typebase_classSTI模型,在我的情况下是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 …
Run Code Online (Sandbox Code Playgroud)

activerecord ruby-on-rails polymorphic-associations

41
推荐指数
4
解决办法
2万
查看次数