Rails 【提供了一般的解决方案看看有没有更好的 顺便 5 楼新问题】多态下的查询(不知道怎么用术语)看到的小伙伴进来看看吧

so_zengtao · 2014年09月15日 · 最后由 ruby_xiaojie 回复于 2015年11月04日 · 2461 次阅读

老习惯先贴代码吧 先看 模型

# Collocation 和 Group 都有 state 和 feature 属性
class Collocation < ActiveRecord::Base
  has_one   :hit,     as: :hitable
  has_many  :sets,    as: :setable
end

class Group < ActiveRecord::Base
  has_one   :hit,     as: :hitable
  has_many  :sets,    as: :setable
end

class Set < ActiveRecord::Base
  belongs_to  :setable,   :polymorphic
  # 我想在下面这个scope里面 取到对应的state 和 feature 的 Collocation 和 Group 怎么写
  # 下面的这个写法不对
  scope :active_sets, -> { includes(:setable).where(setable: { state: 'ACTIVE', feature: true }) }
end

然后看看我在 Controller 里面原来的比较搓的方法

def index
  @sets = Set.all
  @sets = sets.select do |set|
    set.setable.state == "ACTIVE" && set.setable.is_featured == true
  end
end
这样是可以的 但是现在想 这样写

@sets = Set.active_sets # 这里就是上面模型里面我不知道该怎么写的 诸位大侠。

我理解的多态 是一个 容器(也是 C++ 里面的基类)用基类指针数组去找子类特定的属性。。反正好吧就是这样的 有没有小伙伴告诉我这个怎么写 某再次多谢了

这得自己写 sql 的 join 查询吧

#1 楼 @loveltyoic 目前是写的自己的 sql 又臭又长 我整个人都不好了

3 楼 已删除

最后我的解决方法是这样的 不知道大家有没有更加好的方法 顺便我这里还有一个新的问题 看下一个回复

class Set < ActiveRecord::Base
    belongs_to  :setable, :polymorphic => true

    belongs_to  :collocation, foreign_key: :setable_id, foreign_type: :collocation
    belongs_to  :group, foreign_key: :setable_id, foreign_type: :group
    has_one  :hit, :through => :setable 

    scope :active_sets, -> { includes(:collocation, :group).where(collocations: {state: 'ACTIVE', is_featured: true }) or where(groups: { state: 'ACTIVE', is_featured: true })}

end

最新的问题在这里 就是排序了 假如只对 Collcation 排序

@collocations = Collcation.all
@collocations = @collocations.joins(:hit).order('count DESC')

现在要在多态的这个容器层 对这个 hit 排序 - - 大家有木有解决办法 或者遇到过这样的问题

你的两个问题其实都由一个问题引起的,就是 Collocation 和 Group 是两个不同的类,但需要统一查询,由此才引起的 where, join, order 一系列麻烦。

解决方法:使用 STI,让 Collocation 和 Group 都使用一个基类,查询就用基类去查询,你这个应用场景是适合使用 STI 的。

create_table :base_groups do |t|
  t.string :type, limit: 50
end

class BaseGroup < ActiveRecord::Base
  has_many :hit
  has_many :sets
end

class Collocation < BaseGroup
end

class Group < BaseGroup
end

class Set < ActiveRecord::Base
  # 也不需要 polymorphic 了
  belongs_to :setable, class_name: "BaseGroup"
end

其他 scope 什么的该怎么做就怎么做,因为都使用的基类,查询就跟非 polymorphic 的查询一样写。

#6 楼 @darkbaby123 嘿嘿 谢谢你了 我今天上午已经使用 STI 重构完了 同 武汉 握爪

@so_zengtao 你也是武汉的?握爪~

完全看不懂

#8 楼 @darkbaby123 你在武汉哪里 0.0

#9 楼 @cifery 同志 你真萌 哈哈

@so_zengtao 看我的 profile 就看得到啊。

完全看不懂,我死定了

ringokun 多态情况下关联表查询问题 提及了此话题。 05月19日 17:37
需要 登录 后方可回复, 如果你还没有账号请 注册新账号