【问题标题】:Rails 4 respond_with include association with WHERERails 4 respond_with 包括与 WHERE 的关联
【发布时间】:2015-05-29 13:55:09
【问题描述】:

我正在使用 rails respond_with 向客户端发送 JSON 响应,我正在尝试弄清楚如何在我的关联中使用 respond_with 中的 includes 选项以及 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

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

【问题讨论】:

  • 您可以在 movies 变量上添加 where 语句 - 类似于 movies = Movie.where(user_id: @user.id).order...
  • @abbott567,这行不通。提问者架构中的 Movie 模型上没有 user_id 列。该查询将引发异常。

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


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 这行不通 - 我仍在获取特定电影的所有评分,但我只想要该用户对该特定电影的评分
  • 我真的很困惑 - 虽然这应该可以,但我只得到了 Movies 表的字段,而不是加入的 Ratings 表
  • @user2635088,您是否在控制台中尝试过此查询,并确认它没有返回字段?您可能需要修改 respond_with 参数;我不太熟悉Responder 以及它如何生成 JSON 响应。我刚刚检查了一下,查询在一个小测试中正常工作;我将在上面发布生成的 SQL。
  • 是的,这就是控制台中查询的样子:SELECT "movies"."id" AS t0_r0, "movies"."name" AS t0_r1, "movies"."image" AS t0_r2, "ratings"."id" AS t1_r0, "ratings"."user_id" AS t1_r1, "ratings"."design_id" AS t1_r2, "ratings"."value" AS t1_r3, "ratings"."created_at" AS t1_r4, "ratings"."updated_at" AS t1_r5 FROM "movies" INNER JOIN "ratings" ON "ratings"."design_id" = "movies"."id" WHERE "movies"."id" = $1 AND "ratings"."user_id" = $2 [["id", 4], ["user_id", 1]] 我已经确认 user_id = 1 和 movie_id = 4 的评分存在
  • 当我执行movies.as_json(include: :ratings) 时,它看起来工作正常。也许你只需要像一开始那样做respond_with(movies, include: :ratings)? (尽管就像我说的,我对respond_with 了解不多。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 2022-10-23
  • 2015-04-19
  • 1970-01-01
  • 2022-07-08
相关资源
最近更新 更多