I'm using rails respond_with
to send a JSON response to the client, and I'm trying to figure out how to use the includes
option in respond_with
along with a where
clause in my association
Here are my models:
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
In my controller action, I have:
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
However, this is responding with ALL the ratings for those three movies. I want to restrict it the ratings of just that particular user
You could do this:
Although that doesn't make much sense in a
create
action.NOTE
The
movies
query above will generate the following SQL (2 commands; note that some of your fields will differ since I'm using bare versions of your models):