0

我正在使用 railsrespond_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

但是,这是对这三部电影的所有收视率的回应。我想限制该特定用户的评级

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 回答