私はRails 3とpostgresqlを使用しています。私は以下のジャンルを持っています:ロック、雰囲気、オルタナティブ、ハウス。activerecordでアクティブなジャンルを取得するには?
また、2人のユーザーが登録されています。 1つはのロック、もう1つはハウスのジャンルです。私はロックや家のジャンルのオブジェクトを返す必要があります。
これを行うには2つの方法があります。一つは、グループを使用している:
Genre.group('genres.id, genres.name, genres.cached_slug, genres.created_at, genres.updated_at').joins(:user).all
そして、他のDISTINCT使用:
Genre.select('DISTINCT(genres.name), genres.cached_slug').joins(:user)
両方が同じ所望の結果を返します。しかし、どちらが優れたパフォーマンス賢明ですか?
ActiveRecord::StatementInvalid: PGError: ERROR: column "genres.id" must appear in the GROUP BY clause or be used in an aggregate function
: SELECT genres.id FROM "genres" INNER JOIN "users" ON "users"."genre_id" = "genres"."id" GROUP BY genres.name
Genre.select( 'DISTINCT(genres.name)、genres。*')。joins(:user) –