我有 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 索引。 我想要一个 bool 属性,代表其用户拥有一部或多部经过验证的手机的服务。
所以在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
->同样的问题:属性对于每个拥有手机的用户都是正确的,无论是否经过验证,是否已被破坏。
我不擅长 SQL 语法,有人可以帮我解决这个问题吗? 谢谢
最佳答案
第二种方法就是您所追求的 - 即使您加入特殊关联,默认情况下表别名也将是表名称 - 因此,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
关于thinking-sphinx - 考虑具有多个连接和条件的 sphinx 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20892716/