我正在使用 Rails 3.2.8 进行开发,我想将此排序转换为 Rails 范围。
class Doc < ActiveRecord::Base
has_many :denotations
def same_sourceid_denotations_count
denotation_doc_ids = Doc.where(:sourceid => self.sourceid).collect{|doc| doc.id}
Denotation.select('doc_id').where('doc_id IN (?)', denotation_doc_ids).size
end
end
class Denotation < ActiveRecord::Base
belongs_to :doc
end
ans 排序如下
@docs = docs.sort{|a, b| b.same_sourceid_relations_count <=> a.same_sourceid_relations_count}
我在下面写了范围,但不起作用。
scope :same_sourceid_docs_denotations_count
select('docs.*, docs.sourceid = docs.sourceid AS same_sourceid_doc_ids, COUNT(denotations.doc_id IN (same_sourceid_doc_ids)) AS same_sourceid_docs_denotations_count')
.group('docs.id')
.order('same_sourceid_docs_denotations_count DESC')
出错了。
PG::Error: ERROR: missing FROM-clause entry for table "denotations"
LINE 1: ...d = docs.sourceid AS same_sourceid_doc_ids, COUNT(denotation...
^
: SELECT docs.*, docs.sourceid = docs.sourceid AS same_sourceid_doc_ids, COUNT(denotations.doc_id IN (same_sourceid_doc_ids)) AS same_sourceid_docs_denotations_count FROM "docs" WHERE "docs"."sourcedb" = 'PubMed' GROUP BY docs.id ORDER BY same_sourceid_docs_denotations_count DESC LIMIT 10 OFFSET 0
.group('docs.id')
.order('same_sourceid_docs_denotations_count DESC')
此排序步骤如下
- 查找所有具有相同 sourceid 的文档并获取这些 id。
- 计算上面 id 中具有 doc_id 的表示。
按上述符号数对文档进行排序。
<Doc id: 1, sourceid: 111>
<Doc id: 2, sourceid: 111>
<Denotation id: 1, doc_id: 1 >
<Denotation id: 2, doc_id: 2 >
<Denotation id: 3, doc_id: 2 >
=> 与 sourceid 111 相关的表示计数应为 3<Doc id: 3, sourceid: 222>
<Denotation id: 4, doc_id: 3 >
=> 与 sourceid 222 相关的 denotation 计数应该是 1
有任何想法吗?