加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – ActiveRecord,has_many:through,与STI的多态

发布时间:2020-12-16 22:37:59 所属栏目:百科 来源:网络整理
导读:在 ActiveRecord,has_many :through,and Polymorphic Associations年,OP的例子要求忽略可能的外星人和人(超类)的超类.这就是我的问题所在. class Widget ActiveRecord::Base has_many :widget_groupings has_many :people,:through = :widget_groupings,:sou
在 ActiveRecord,has_many :through,and Polymorphic Associations年,OP的例子要求忽略可能的外星人和人(超类)的超类.这就是我的问题所在.
class Widget < ActiveRecord::Base
  has_many :widget_groupings

  has_many :people,:through => :widget_groupings,:source => :person,:source_type => 'Person'
  has_many :aliens,:source => :alien,:source_type => 'Alien'
end

SentientBeing < ActiveRecord::Base
  has_many :widget_groupings,:as => grouper
  has_many :widgets,:through => :widget_groupings
end


class Person < SentientBeing
end

class Alien < SentientBeing
end

在这个修改示例中,Alien和Person的grouper_type值现在都由Rails作为SentientBeing存储(Rails查找此grouper_type值的基类).

在这种情况下,修改Widget中的has_many的类型进行过滤的正确方法是什么?我想要能够做Widget.find(n).people和Widget.find(n).aliens,但是目前这两种方法(.people和.aliens)都返回空set [],因为grouper_type始终是SentientBeing.

解决方法

你是否尝试过最简单的事情 – 添加:has_many的条件:通过?

换句话说,这样的东西(在widget.rb中):

has_many :people,:conditions => { :type => 'Person' },:source => :grouper,:source_type => 'SentientBeing'
has_many :aliens,:conditions => { :type => 'Alien' },:source_type => 'SentientBeing'

JamesDS是正确的,需要一个联接 – 但它不是写在这里,因为has_many:通过关联已经在做.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读