【问题标题】:Polymorphic Has_many Association with Polymorphic Class [closed]多态 Has_many 与多态类的关联[关闭]
【发布时间】:2018-03-01 08:15:47
【问题描述】:

我的多态关联有问题。

角色.rb

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

结构.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

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

#&lt;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"&gt;]

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

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

【问题讨论】:

  • 不清楚您的要求。请改写它并明确您要完成的工作。

标签: ruby-on-rails relationship


【解决方案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

【讨论】:

  • 感谢您的回复,我使用“范围”或自定义函数来执行此操作...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-28
  • 1970-01-01
  • 2016-03-20
  • 1970-01-01
  • 2010-12-13
  • 1970-01-01
相关资源
最近更新 更多