lil_dippa
lil_dippa

Reputation: 177

Rails Active Record: Query by association value multiple iterations

I have a rails app where I am trying to retrieve Shoes if they have certain colors. Currently my code is:

@shoes = Shoe.all
shoe_colors = params[:shoe][:colors].split('/')

shoe_colors.each do |color|
    @shoes = @shoes.joins(:colors).where('colors.name = ?', color)
end

I am sending all the colors in a string and then splitting it. It works great if there is only one color that I am trying to match, however if I am sending multiple colors it returns no results. I believe that I am somehow excluding all other colors on the first iteration, but I am pretty confused as to why or how I could not. I appreciate all help, Thanks.

Upvotes: 0

Views: 60

Answers (2)

Lam Phan
Lam Phan

Reputation: 3811

i assume that you don't have any problem with colors params, that mean shoe_colors = params[:shoe][:colors].split('/') ok, so your query should be

shoe_colors = params[:shoe][:colors].split('/')
@shoes = Shoe.joins(:colors)
.where('colors.name IN (?)', shoe_colors)
.group(:id).having(Arel.star.count.eq(shoe_colors.size))

Upvotes: 1

Sachin Singh
Sachin Singh

Reputation: 1108

There is no need of looping through the shoe_colors list for getting all the shoes with matching colors. Here is how you can get all the matching data:

shoe_colors = params[:shoe][:colors].split('/')
@shoes = Shoe.all.joins(:colors).where(colors: { name: shoe_colors })

Upvotes: 0

Related Questions