【发布时间】: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