Rails 4 respond_with包括与WHERE的关联

时间:2015-05-29 13:55:10

标签: ruby-on-rails-4 activerecord responders

我使用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

但是,这是对这三部电影的所有评分做出回应。我想限制它只是特定用户的评级

1 个答案:

答案 0 :(得分: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]]