为什么我的多态类型是我的模型继承的类?

时间:2018-06-11 19:54:17

标签: ruby-on-rails polymorphic-associations

我有一个继承自其他基础模型的模型:

class Instructor < User

我有另一个具有多态关联的模型:

class SiteResource < ApplicationRecord
  belongs_to :site
  belongs_to :resource,  polymorphic: true
end

但是当我创建新对象时,它具有资源类型User,而不是Instructor

irb(main):005:0> SiteResource.create(site: Site.first, resource: Instructor.first)
+----+---------+-------------+---------------+--------+-------------------------+-------------------------+
| id | site_id | resource_id | resource_type | status | created_at              | updated_at              |
+----+---------+-------------+---------------+--------+-------------------------+-------------------------+
| 2  | 1       | 21          | User          | 1      | 2018-06-11 19:47:29 UTC | 2018-06-11 19:47:29 UTC |
+----+---------+-------------+---------------+--------+-------------------------+-------------------------+

这是:

  1. 意?
  2. 有利?
  3. 坏消息?
  4. 配置?

1 个答案:

答案 0 :(得分:0)

直接来自文档的一个例子,文字副本粘贴,因为我无法解释它,因为它们

class Asset < ActiveRecord::Base
  belongs_to :attachable, polymorphic: true
end

class Post < ActiveRecord::Base
  has_many :assets, as: :attachable         # The :as option specifies the polymorphic interface to use.
end

@asset.attachable = @post
  

将多态关联与单表继承(STI)结合使用有点棘手。为了使关联按预期工作,请确保将STI模型的基本模型存储在多态关联的类型列中。要继续上面的资产示例,假设有一些访客帖子和成员帖子使用了STI的posts表。在这种情况下,posts表中必须有一个type列

注意:在分配可附加的时,正在调用attachable_type =方法。可附加的 class_name作为String 传递。

class Asset < ActiveRecord::Base
  belongs_to :attachable, polymorphic: true

  def attachable_type=(class_name)
     super(class_name.constantize.base_class.to_s)
  end
end

class Post < ActiveRecord::Base
  # because we store "Post" in attachable_type now dependent: :destroy will work
  has_many :assets, as: :attachable, dependent: :destroy
end

class GuestPost < Post
end

class MemberPost < Post
end

您需要的官方文档:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations