多态Has_many与多态类的关联

时间:2018-03-01 08:15:47

标签: ruby-on-rails relationship

我的多态关联存在问题。

role.rb

class Role < ActiveRecord::Base
  belongs_to :resource, polymorphic: true
end

structure.rb

class Structure < ActiveRecord::Base
  has_many :roles, as: :resource
end

association.rb

class Association < Structure
end

我有另一个名为User的模型,我创建了像Rolify这样的角色。

def add_role role_name, resource = nil
  role = Role.find_or_create_by(name: role_name.to_s,
    resource_type: (resource.is_a?(Class) ? resource.to_s : resource.class.name if resource),
    resource_id: (resource.id if resource && !resource.is_a?(Class)))

  if !roles.include?(role)
    self.roles << role
    self.save
  end
  role
end

因此,当我为具有关联的用户创建角色时,我有:

#<Role id: 2, name: "president", resource_id: 1, resource_type: "Association", created_at: "2018-02-28 23:04:20", updated_at: "2018-02-28 23:04:20">]

但是当我尝试从Association获取所有角色时,这就是SQL:

SELECT `roles`.* FROM `roles`  WHERE `roles`.`resource_id` = 1 AND `roles`.`resource_type` = 'Structure'

1 个答案:

答案 0 :(得分:1)

看看Why polymorphic association doesn't work for STI if type column of the polymorphic association doesn't point to the base model of STI? - 看起来Rails不支持开箱即用(至少通过Rails 4.2 - 不确定你使用的是哪个版本)。看起来最好的解决方案可能是覆盖_type方法。看起来可能还有一个宝石:https://github.com/appfolio/store_base_sti_class