Rails 4 respond_with 包括与 WHERE 的关联

Rails 4 respond_with include association with WHERE

我正在使用 rails respond_with 向客户端发送 JSON 响应,我正在尝试弄清楚如何使用 includes 选项在 respond_with 以及我的协会

中的 where 子句

这是我的模型:

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

但是,这是对这三部电影的所有评分的回应。我想将其限制为仅该特定用户的评分

你可以这样做:

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]]