activerecord - Rails 4 respond_with include association with WHERE -


i'm using rails respond_with send json response client, , i'm trying figure out how use includes option in respond_with along where clause in association

here 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 controller action, have:

def create    movies = movie.order("random()").limit(3)    respond_with(movies, include: :ratings)    // i'd     // respond_with(movies, include: :ratings user: current_user)  end 

however, responding ratings 3 movies. want restrict ratings of particular user

you this:

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 

although doesn't make sense in create action.

note

the movies query above generate following sql (2 commands; note of fields differ since i'm using bare versions of models):

select distinct "movies"."id" "movies"  inner join "ratings" on "ratings"."movie_id" = "movies"."id" "ratings"."user_id" = ?  order random() limit 3  select "movies"."id" t0_r0, "movies"."name" t0_r1, "movies"."created_at" t0_r2,  "movies"."updated_at" t0_r3, "ratings"."id" t1_r0, "ratings"."user_id" t1_r1,  "ratings"."movie_id" t1_r2, "ratings"."created_at" t1_r3, "ratings"."updated_at" t1_r4  "movies" inner join "ratings" on "ratings"."movie_id" = "movies"."id"  "ratings"."user_id" = ? , "movies"."id" in (1) order random() [["user_id", 1]] 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -