环境:RoR 3.2 + Postgres
我创建了一个包含2个文字属性的services
表:title
和description
我想进行以下全文搜索:
SELECT * FROM (
SELECT DISTINCT ON (s.id) s.*,
ts_rank_cd(s.service_tsv, query) AS rank
FROM to_tsquery('red | drawing | fun') AS query,
services AS s
WHERE (s.service_tsv @@ query)
ORDER BY s.id DESC
) AS sub ORDER BY rank DESC;
SQL语句就像一个魅力,但我怎么把它翻译成Rails ORM:
Service.joins(???).where(???).uniq
答案 0 :(得分:2)
Service.find_by_sql(%q{SELECT * FROM (
SELECT DISTINCT ON (s.id) s.*,
ts_rank_cd(s.service_tsv, query) AS rank
FROM to_tsquery('red | drawing | fun') AS query,
services AS s
WHERE (s.service_tsv @@ query)
ORDER BY s.id DESC
) AS sub ORDER BY rank DESC})
指导http://guides.rubyonrails.org/active_record_querying.html#finding-by-sql