思考具有多个连接和条件的sphinx索引

时间:2014-01-02 21:59:59

标签: thinking-sphinx

我有3个型号:用户has_one服务和用户Has_many手机(已验证或未验证,是否已销毁)

Class Phone < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
     has_one :service
     has_many :phones
     has_many :verified_phones, -> {where('verified_at IS NOT NULL AND destroyed_at IS NULL')}, class_name: 'Phone'
end

class Service < ActiveRecord::Base
    belongs_to :user
    has_many :phones, through: :user
    has_many :verified_phones, through: :user
end

我想在模型服务上定义TS索引。 我想要一个boolean-faceted属性,表示用户拥有一个或多个经过验证的手机的服务。

所以在reading this post I tried之后:

join verified_phones
has 'COUNT(verified_phones.id) > 0', as: :user_phone_verified, type: :boolean, facet: true

但在'字段列表'中向我发送错误“未知列'verified_phones.id'”(帖子中出现同样的错误)

然后我试了

join verified_phones
has 'COUNT(phones.id) > 0', as: :user_phone_verified, type: :boolean, facet: true
-> but result are wrong : attribute is true for every user that have a phone, verified or not, destroyed or not.

然后我试了

join phones
has 'COUNT(phones.verified_at IS NOT NULL AND phones.destroyed_at IS NULL) > 0', as: :user_phone_verified, type: :boolean, facet: true

- &GT;同样的问题:对于每个拥有电话,验证与否,被破坏的用户,属性都是真的。

我对SQL语法不太满意,有人可以帮我解决这个问题吗? 感谢

2 个答案:

答案 0 :(得分:1)

第二种方法就是您所追求的 - 即使您加入特殊关联,表别名默认为表名 - 因此,phones.id。

那就是说,回来的东西似乎不对。也许以下是:

join verified_phones
has "SUM(CASE WHEN phones.id IS NULL THEN 0 ELSE 1 END) > 0",
  as: :user_phone_verified, type: :boolean, facet: true

答案 1 :(得分:1)

我明白了: 我应该更精确地使用我的关联定义的语法:

has_many :verified_phones, -> {where('verified_at IS NOT NULL AND destroyed_at IS NULL')}, class_name: 'Phone'

应该是:

has_many :verified_phones, -> {where('phones.verified_at IS NOT NULL AND phones.destroyed_at IS NULL')}, class_name: 'Phone'

我的用户模型具有相同的属性“destroyed_at” - &gt;生成的SQL在错误的表中查找此属性。

因此,通过此更正,两种语法都可以工作:

我的初始:

join verified_phones
has 'COUNT(phones.id) > 0', as: :user_phone_verified, type: :boolean, facet: true

或@Pat建议:

    has "SUM(CASE WHEN phones.id IS NULL THEN 0 ELSE 1 END) > 0",
  as: :user_phone_verified, type: :boolean, facet: true

但我对此并不是很舒服,因为我觉得可能会混淆这个名为“phone”的表别名。如果我需要加入相同的索引电话和已验证的电话,会发生什么?

但是现在它解决了我的问题,所以谢谢你@Pat!