2013-04-16 84 views
0

我有三種模型,故事,發佈和標記。 Story與Post有一對多的關係,與Tag有多對多的關係。嘗試鏈接使用group_by連接表上的搜索鏈接文本搜索時出現錯誤

我用下面的範圍來搜索具有匹配的標籤陣列中的至少一個標籤故事:

scope :in_tags, lambda {|category_array, tag_array| 
          Story.joins('LEFT OUTER JOIN stories_tags ON stories_tags.story_id = stories.id'). 
            joins('LEFT OUTER JOIN tags ON tags.id = stories_tags.tag_id'). 
            where("tags.name in (:tag_array)", :tag_array => tag_array). 
            group("stories.id") 
    } 

請注意,我用GROUP_BY,這樣的範圍不返回一個故事多次如果該故事有多個匹配的標籤。

我用下面的pg_search_scope搜索故事或職位與指定的文本:

pg_search_scope :with_text, 
        :against => :title, 
        :using => { :tsearch => { :dictionary => "english" }}, 
        :associated_against => { :posts => :contents } 

這些示波器的兩個正常工作相互獨立的。當我嘗試鏈在一起,但是,我體驗到PostgreSQL的錯誤:

ActiveRecord::StatementInvalid (PG::Error: ERROR: column "pg_search_79dd68cf7f962ac568b3d7.pg_search_c5f43d73058486e1799d26" must appear in the GROUP BY clause or be used in an aggregate function 
LINE 1: ...e"::text, '')) || to_tsvector('english', coalesce(pg_search_... 
                  ^
: SELECT "stories".*, ((ts_rank((to_tsvector('english', coalesce("stories"."title"::text, '')) || to_tsvector('english', coalesce(pg_search_79dd68cf7f962ac568b3d7.pg_search_c5f43d73058486e1799d26::text, ''))), (to_tsquery('english', ''' ' || 'track' || ' ''')), 0))) AS pg_search_rank FROM "stories" LEFT OUTER JOIN stories_tags ON stories_tags.story_id = stories.id LEFT OUTER JOIN tags ON tags.id = stories_tags.tag_id LEFT OUTER JOIN (SELECT "stories"."id" AS id, string_agg("posts"."contents"::text, ' ') AS pg_search_c5f43d73058486e1799d26 FROM "stories" INNER JOIN "posts" ON "posts"."story_id" = "stories"."id" GROUP BY "stories"."id") pg_search_79dd68cf7f962ac568b3d7 ON pg_search_79dd68cf7f962ac568b3d7.id = "stories"."id" WHERE (tags.name in (sports') AND (((to_tsvector('english', coalesce("stories"."title"::text, '')) || to_tsvector('english', coalesce(pg_search_79dd68cf7f962ac568b3d7.pg_search_c5f43d73058486e1799d26::text, ''))) @@ (to_tsquery('english', ''' ' || 'track' || ' ''')))) GROUP BY stories.id ORDER BY latest_post_id DESC LIMIT 5000 OFFSET 0): 

有沒有辦法與要求與GROUP_BY子句的連接表一個範圍內使用pg_search?

回答

0

我最終不得不從.group()方法(我似乎無法使用pg_search)切換到select("DISTINCT(stories.id), stories.*)。我也利用了ActiveRecords#preload這麼急切地加載相關的標籤記錄