Rails: Search method breaks PostgreSQL, alternatives?
I have the following method in my app:
def self.tagged_with( string )
array = string.split(',').map{ |s| s.lstrip }
joins(:tags).where('tags.name' => array ).group('photos.id')
end
This is searching photos, which have many tags through taggings.
This method takes a comma separated list of tags and returns any photos that have associated tags with the given names.
The problem is, it breaks PostgreSQL with the following error message:
ActionView::Template::Error (PGError: ERROR: column "photos.custom_title" must appear in the GROUP BY clause or be used in an aggregate function
: SELECT "photos".* FROM "photos" INNER JOIN "taggings" ON "photos"."id" = "taggings"."phot开发者_JAVA技巧o_id" INNER JOIN "tags" ON "tags"."id" = "taggings"."tag_id" WHERE "tags"."name" IN ('village') AND ("photos".collection_id = 1) GROUP BY photos.id LIMIT 20 OFFSET 0):
In another somewhat similar question an answerer suggested that whenever using .group()
it was necessary to include all columns in the table. This seems insane to me -- what the heck is the point of .group
if you can only use it by typing up all the fields in your model. That's brittle, and just a bad idea overall.
Can anyone suggest an alternative way to make this method work with PostgreSQL?
Take a look at this article.
One of the suggestions ("Option 2") is to add select("distinct photos.*")
before your join. I've never done this but it seems worth a try; certainly better than putting every selected field into an aggregate function.
精彩评论