复杂的Postgres SQL到RoR ORM

时间:2013-03-28 23:30:43

标签: sql ruby-on-rails postgresql orm

环境:RoR 3.2 + Postgres

我创建了一个包含2个文字属性的services表:titledescription

我想进行以下全文搜索:

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 

1 个答案:

答案 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