我这里有一个多态性关联和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文档,我必须将borrowable_type设置为STI模型的base_class,在我的例子中是Staff.

The question is: Why doesn't it work if the 100 set to STI class?

一些测试证明了这一点:

# 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

但似乎只有Staff个例子是正确的.结果是:

# 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文档给出了以下建议:

结合使用单一多态表

在您的情况下,基本模型将是"Staff",即所有项目的"可borrow _类型"应为"Staff",而不是"Guard".通过使用"变成":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相关问答推荐

Ruby线程使用互斥处理并发问题

错误AESGCMOpen获取密码:消息身份验证失败:Golang解密GCM

ActiveRecord::声明在类别中无效#new

为什么有时会出现类型错误没有将 StringIO 隐式转换为 String?Ruby /导轨

Ruby on Rails 中的多种布局

Rails 模型 - 以 ID 作为自定义列的自定义主键

如何从 Ruby on Rails 应用程序返回正确的 HTTP 错误代码

注册表单上是否需要 CSRF 保护?

理解 Gemfile.lock:删除 Gemfile.lock 然后再次运行 bundle install 可以吗?

价格字段的字符串、小数或浮点数据类型?

rails 方法获取模型的关联名称

Rails 引擎中的迁移?

如何在 Ruby 中生成随机日期?

RubyMine - 关闭在空行中间单击的功能

登录delay_job?

Rspec - Rails - 如何遵循重定向

如何翻译 ActiveRecord 模型类名称?

如何创建迁移以仅在索引存在时删除索引,而不是在不存在时抛出异常?

ruby 方法名称中的变量

如何更改 Rails 3 控制器中视图文件的默认路径?