0

Rails を使用して JSON 応答をクライアントに送信しています。また、関連付けの節と一緒にオプションrespond_withを使用する方法を見つけようとしています。includesrespond_withwhere

ここに私のモデルがあります:

class User < ActiveRecord::Base
   has_many :ratings
   has_many :movies, through: :ratings
end

class Rating < ActiveRecord::Base
   belongs_to :user
   belongs_to :movie
end

class Movie < ActiveRecord::Base
   has_many :ratings
   has_many :users, through: :ratings
end

私のコントローラーアクションには、次のものがあります。

def create
   movies = Movie.order("RANDOM()").limit(3)
   respond_with(movies, include: :ratings)
   // I'd like to do something like 
   // respond_with(movies, include: :ratings WHERE user: current_user)

end

ただし、これはこれら 3 つの映画のすべての評価で応答しています。特定のユーザーだけの評価に制限したい

4

1 に答える 1

0

あなたはこれを行うことができます:

def create
  movies = Movie.order("RANDOM()").limit(3)
  # EDIT
  # movies = movies.merge(current_user.movies).includes(:ratings)
  movies = movies.joins(:ratings).merge(current_user.ratings).includes(:ratings)
  respond_with(movies)
end

それはアクションではあまり意味がありませんがcreate

ノート

上記のmoviesクエリは、次の SQL を生成します (2 つのコマンド。モデルのベア バ​​ージョンを使用しているため、一部のフィールドが異なることに注意してください)。

SELECT DISTINCT "movies"."id" FROM "movies" 
INNER JOIN "ratings" ON "ratings"."movie_id" = "movies"."id"
WHERE "ratings"."user_id" = ?  ORDER BY RANDOM() LIMIT 3

SELECT "movies"."id" AS t0_r0, "movies"."name" AS t0_r1, "movies"."created_at" AS t0_r2, 
"movies"."updated_at" AS t0_r3, "ratings"."id" AS t1_r0, "ratings"."user_id" AS t1_r1, 
"ratings"."movie_id" AS t1_r2, "ratings"."created_at" AS t1_r3, "ratings"."updated_at" AS t1_r4 
FROM "movies" INNER JOIN "ratings" ON "ratings"."movie_id" = "movies"."id" 
WHERE "ratings"."user_id" = ? AND "movies"."id" IN (1) ORDER BY RANDOM() [["user_id", 1]]
于 2015-05-29T14:26:47.527 に答える